是否有一个PHP函数可以在应用之前逃避正则表达式模式?

vfc*_*sts 157 php regex escaping

是否有一个PHP函数可以在应用之前逃避正则表达式模式?

我正在寻找C#Regex.Escape()功能的一些东西.

Tom*_*igh 250

preg_quote() 是你在找什么:

描述

string preg_quote ( string $str [, string $delimiter = NULL ] )
Run Code Online (Sandbox Code Playgroud)

preg_quote()接受str 并在每个作为正则表达式语法一部分的字符前面加一个反斜杠.如果您有一个需要在某些文本中匹配的运行时字符串,并且字符串可能包含特殊的正则表达式字符,这将非常有用.

特殊的正​​则表达式字符是: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

参数

海峡

输入字符串.

分隔符

如果指定了可选的分隔符,它也将被转义.这对于转义PCRE函数所需的分隔符非常有用./是最常用的分隔符.

重要的是,请注意,如果$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 "
// }
Run Code Online (Sandbox Code Playgroud)

  • [@TomHaigh](http://stackoverflow.com/a/1531471/89771)的另一个评论回答,如果你没有为`preg_quote()指定第二个'$ delimiter`参数`**[它赢了" t逃脱任何分隔符](http://codepad.org/6mRuajog)**,甚至不是"默认"(或最常见的)`/`. (10认同)