簡體   English   中英

是否有 PHP function 可以在應用正則表達式模式之前對其進行轉義?

[英]Is there a PHP function that can escape regex patterns before they are applied?

是否有 PHP function 可以在應用正則表達式模式之前對其進行轉義?

我正在尋找類似於 C# Regex.Escape() function 的東西。

preg_quote()就是你要找的:

描述

string preg_quote ( string $str [, string $delimiter = NULL ] )

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 "
// }

使用來自T-Regx 庫的Prepared Patterns會更安全:

$url = 'http://stackoverflow.com/questions?sort=newest';

$pattern = Pattern::prepare(['\s', [$url], '\s']);
                                // ↑ $url is quoted

然后執行正常匹配:

$haystack = "Bla bla http://stackoverflow.com/questions?sort=newest bla bla";

$matches = $pattern->match($haystack)->all();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM