Possible Duplicate:
Is there a PHP function that can escape regex patterns before they are applied?
我想在正则表达式中使用存储在变量中的字符串。 (在 PHP 中)转义字符串以用于(PCRE)正则表达式的最佳方法是什么?
例如,
$text = 'm/z'; // this is the text I want to use as part of my regular expression
$text_regexp = '#' . $text . '#i'; // this is my regular expression
愿意
$text_regexp = '#m/z#i';
但我想要以下正则表达式:
$text_regexp = '#m\/z#i';
这是一个人为的例子,但我想简单地说明这一点。
最佳答案
来自手册:
puts a backslash in front of every character that is part of the regular expression syntax
你也可以将分隔符作为第二个参数传递,它也会被转义。但是,如果您使用 #
作为分隔符,则无需转义 /
关于php - 转义字符串以用于正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4936342/