2013-05-17 51 views
0

我需要刪除"from products where id = 153183"。該id可以改變,所以我需要使用preg_replace刪除單詞「from」後面的所有內容,然後可能使用str_replace從中刪除。我有下面的內容,但是這隻會從字符串中刪除它的最後一個字。任何人都可以提出我需要添加什麼?PHP - 刪除字符串的最後一部分 - preg_replace

//doesn't work 

$str = "select id, productdescription, category, price, code, manufacturer, categoryid from products where id = 153183"; 

$new_str = preg_replace('/from$/', '', $str); 
+2

是否確實需要刪除'FROM'條款,不只是'WHERE'? – raina77ow

+0

不需要正則表達式。特別是在匹配一個簡單的字符串時。 –

+0

是的,我確定我想從他的字符串中刪除。我不知道他的身份證號碼會在字符串中出現,因此如何在沒有註冊表前執行此操作? – LeeTee

回答

0

你可能要像/from.*$/或者乾脆/from.*/

+0

如果'from'這個詞出現多次,你會遇到麻煩。 – Bart

+0

nope ...''*'是貪婪的。 –

+0

像「SELECT roads_from_rome FROM maps」這樣的語句怎麼樣? '\ bfrom \ b'或'\ sfrom \ s'應該有幫助。 – Blazemonger

1

我有點糊塗了您的問題,這應該讓你去,但。

<?php 
$sql = 'SELECT * FROM products WHERE id = 153183'; 
$sql = preg_replace('~from products where id = [0-9]+$~i', '', $sql); 
echo $sql; 
/* 
    SELECT * 
*/ 
2

,你可以這樣做:

$new_str = stristr($str, " from ", true); 

由於是一個reserved word在SQL你不能在其他地方沒有引號或反引號找到這個字(所以我之後和之前添加一個空格) 。

它返回「from」字之前的字符串。

strstr用於區分大小寫的搜索。

UPDATE:正則表達式(不是真的需要這個問題):

$str = 'select id, productdescription, category, price, code, manufacturer, categoryid from products where id = 153183'; 

preg_match('/(.*)\sfrom\s.*$/i', $str, $matches); // i for the insensitive case search 

$new_str = $matches[1]; // Contains what you want 
+0

+爲非正則表達式的解決方案。 –

+1

不會['stristr'](http://www.php.net/manual/en/function.stristr.php)是更好的選擇嗎? – Blazemonger

+0

是的,的確比較好 – antoox

0

你可以使用一個簡單的str_replace。不知道你是如何得到id,因爲它可以改變,我假設你有一個變量。

$str = "select id, productdescription, category, price, code, manufacturer, categoryid from products where id = 153183"; 
$new_str = str_replace("from products where id = " . $id, "", $str) 
+1

'id'的值可以改變。 –

+0

謝謝我錯過了那部分。 –

0
$string = "select id, productdescription, category, price, code, manufacturer, categoryid from products where id = 153183"; 
$part1 = substr("$string",0, strrpos($string,'from products where id ')); 
var_dump($part1); 

由於大部分字符串是靜態的,你可以使用子字符串,最多有問題的部分。

結果:

組合的
string(79) "select id, productdescription, category, price, code, manufacturer, categoryid " 
0

preg_replacestr_replace也將工作:

<?php 

$str = "select id, productdescription, category, price, code, manufacturer, categoryid from products where id = 153183"; 
$id_removed = preg_replace('/\d/', '', $str); //remove dynamic product id 
$new_str = str_replace("from products where id =",'', $id_removed); 
echo $new_str; 


?> 
相關問題