是否有一个PHP函数可以在应用它们之前逃避正则表达式模式?
我正在寻找C#Regex.Escape()
函数的内容。
答案 0 :(得分:243)
preg_quote()
正是您所寻找的:
描述
string preg_quote ( string $str [, string $delimiter = NULL ] )
preg_quote()需要
str
并放置一个 每个角色前面的反斜杠 这是正则表达式的一部分 句法。如果你有一个,这很有用 您需要匹配的运行时字符串 在一些文本和字符串可能 包含特殊的正则表达式字符。特殊的正则表达式 字符是:
. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
参数
STR
输入字符串。
定界符
如果指定了可选分隔符,它也将被转义。这对于转义PCRE函数所需的分隔符非常有用。 /是最常用的分隔符。
重要的是,请注意,如果未指定$delimiter
参数,则delimiter - 用于封装正则表达式的字符(通常为正斜杠(/
))将不会被转义。您通常希望将正在使用的任何分隔符与正则表达式作为$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 "
// }
答案 1 :(得分:0)
您还可以使用Prepared Patterns中的T-Regx library(自动分隔符和处理不安全字符):
$url = 'http://stackoverflow.com/questions?sort=newest';
$pattern = Pattern::prepare(['\s', [$url], '\s']);
// ↑ $url is quoted
然后执行常规的t-regx匹配:
$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";
$matches = $pattern->match($haystack)->all;