0

削除する必要があり"from products where id = 153183"ます。ID は変更される可能性があるため、preg_replace を使用して「from」という単語の後のすべてを削除し、str_replace を使用して from を削除する必要があります。私は以下を持っていますが、これは文字列の最後の場合にのみ単語を削除します。追加する必要があるものを誰かが提案できますか?

//doesn't work

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

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

6 に答える 6

2

あなたはこれを行うことができます:

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

fromは SQL の予約語であるため、この単語は引用符またはバッククォートなしでは見つけることができません (そのため、前後にスペースを追加します)。

「from」単語の前の文字列を返します。

strstr 大文字と小文字を区別する検索用。

更新:正規表現(この質問には実際には必要ありません):

$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
于 2013-05-17T14:50:08.240 に答える
1

/from.*$/おそらく、または単に次のようなものが必要です/from.*/

于 2013-05-17T14:47:30.493 に答える
1

私はあなたの質問に少し混乱していますが、これでうまくいくはずです。

<?php
$sql = 'SELECT * FROM products WHERE id = 153183';
$sql = preg_replace('~from products where id = [0-9]+$~i', '', $sql);
echo $sql;
/*
    SELECT * 
*/
于 2013-05-17T14:49:57.943 に答える
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 "
于 2013-05-17T14:54:34.550 に答える
0

シンプルなstr_replace. ID は変更される可能性があるため、どのように 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)
于 2013-05-17T14:50:24.920 に答える