开发者

php variable in regex?

开发者 https://www.devze.com 2023-01-15 11:57 出处:网络
I have a variable $word and I\'d like to match it in my select statement somethig like this: \"select * from t开发者_如何学运维able where column regex \'[0-9]$word\'\"

I have a variable $word and I'd like to match it in my select statement somethig like this: "select * from t开发者_如何学运维able where column regex '[0-9]$word'" but this doesnt work, so how can i put a variable in a regular exprssion?

Thank you


You must only put it correctly in SQL query, for example:

mysql_query("SELECT * FROM table WHERE column REGEXP 'prefix_".$word."'");

But you need to remember that the variable data needs to be properly escaped, i think that addslashes() would be enough.


You could try using preg_quote() to escape your string:

$sql = "select * from table where column regexp '[0-9]" . preg_quote($word) . "'";

There will be some issues because MySQL (assuming this is your DB) may have a completely different idea of which characters are special than PCRE.

0

精彩评论

暂无评论...
验证码 换一张
取 消