是否有 PHP 函数可以转义 RegEx 模式以防止它们在另一个 RegEx 模式中使用时被应用?
我正在寻找类似于 C# 的东西Regex.Escape() https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx功能。
preg_quote() http://php.net/preg_quote是您正在寻找的:
描述
string preg_quote ( string $str [, string $delimiter = NULL ] )
preg_quote() takes str
并放一个
每个字符前面的反斜杠
这是正则表达式的一部分
句法。如果您有一个
您需要匹配的运行时字符串
在某些文本和字符串中可能
包含特殊的正则表达式字符。
特殊的正则表达式
字符是:. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
参数
str
输入字符串。
分隔符
如果指定了可选分隔符,它也会被转义。这对于转义 PCRE 函数所需的分隔符很有用。 / 是最常用的分隔符。
重要的是,请注意,如果$delimiter
未指定参数,则分隔符 http://php.net/manual/en/regexp.reference.delimiters.php- 用于括起正则表达式的字符,通常是正斜杠(/
) - 不会被转义。您通常会希望传递与正则表达式一起使用的任何分隔符作为$delimiter
争论。
示例 - 使用preg_match
查找被空格包围的给定 URL 的出现次数:
$url = 'http://stackoverflow.com/questions?sort=newest';
// preg_quote escapes the dot, question mark and equals sign in the URL (by
// default) as well as all the forward slashes (because we pass '/' as the
// $delimiter argument).
$escapedUrl = preg_quote($url, '/');
// We enclose our regex in '/' characters here - the same delimiter we passed
// to preg_quote
$regex = '/\s' . $escapedUrl . '\s/';
// $regex is now: /\shttp\:\/\/stackoverflow\.com\/questions\?sort\=newest\s/
$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";
preg_match($regex, $haystack, $matches);
var_dump($matches);
// array(1) {
// [0]=>
// string(48) " http://stackoverflow.com/questions?sort=newest "
// }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)