转义字符串以在正则表达式中使用
我想在正则表达式中使用存储在变量中的字符串。 (在 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';
But I would Want 以下正则表达式:
$text_regexp = '#m\/z#i';
这是一个人为的示例,但我想简单地说明这一点。
Possible Duplicate:
Is there a PHP function that can escape regex patterns before they are applied?
I want to use a string stored in a variable in a regular expression. What's the best way (in PHP) to escape a string for use in a (PCRE) regular expression?
For example,
$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
Would give
$text_regexp = '#m/z#i';
But I would want the following regular expression:
$text_regexp = '#m\/z#i';
This is a contrived example, but I wanted to illustrate the point simply.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
preg_quote
来自手册:
您还可以将分隔符作为第二个参数传递,它也会被转义。但是,如果您使用
#
作为分隔符,则无需转义/
preg_quote
From the manual:
You can also pass the delimiter as the second parameter and it will also be escaped. However, if you're using
#
as your delimiter, then there's no need to escape/
您必须使用
preg_quote
函数:必须作为整个单词匹配的
$keyword
示例:You must use the
preg_quote
function:Example of a
$keyword
that must match as a whole word:检查这个。您可以使用 preg_quote();。
Check this. You can use preg_quote();.
所有这些答案都是正确的,只有元字符需要转义。
可惜 php 没有像 preg_match([operator]/$var/) 这样的正则表达式运算符,因此分隔符可以作为引用代理。这样 delimeter 就不必在外部 $var 中引用。 (Perl 有 m//,s/// 或 =~ 运算符)
preg_quote 是一个很好的方法,不幸的是,有时你想匹配文字 '\char' 而不将其转义为 '\char'实例,并逃避其余的。 preg_quote() 的选择不多。
您可以从字面上设置自己的 php 函数来引用元字符(或在 preg_quote() 之后去掉引号)。
就像将所有
/([{}\[\]()^\$.|*+?\\<>$delim])/
替换为\\$1或其他东西。设置 $delim,和/或删除可能的转义符或任何其他您不想转义的元字符。
只是我的 $.02
All these answers are correct, only the metachars need to be escaped.
Its kind of too bad that php doesen't have a regex operator like preg_match([operator]/$var/) so the delimeters could be the quoting agent. This way delimeter wouldn't have to be quoted in an external $var. (Perl has this with m//,s/// or =~ operators)
The preg_quote is a nice way to do this, unfortunately, sometimes you want to match literal '\char' without it being escaped to '\char' for instance, and escape the rest. Not many choices with preg_quote().
You could literally set up your own php functions that does quoting of metachars (or take off a quote after preg_quote() ).
like a replace all
/([{}\[\]()^\$.|*+?\\<>$delim])/
with\\$1
or something. Set the $delim, and/or take out possibly the escape or any other metachars you don't want escaped.Just my $.02