You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在preg_quote()中排除竖线转义以适配preg_match正则匹配?

解决方案

问题出在你先拼接分支符|再整体转义,导致|被转义成\|,失去了正则中“或”的分支作用。正确的做法是先单独转义数组中的每个路径元素,再用|拼接:

$url = 'example.com/path/to/!another';
$arr = ['path/to/!page', 'path/to/!another'];

// 先对每个路径单独转义正则特殊字符
$escapedPaths = array_map(function($path) {
    return preg_quote($path, '/');
}, $arr);

// 再用|拼接成分支匹配模式
$pattern = implode('|', $escapedPaths);

if(preg_match('/(' . $pattern . ')/', $url)) {
    echo 'The input url contains one of the paths in array!';
}

为什么这样有效?

  • preg_quote($path, '/')会转义单个路径里的所有正则特殊字符(比如/转成\/,!转成\!),此时还未引入分支符|,所以不会误转义它。
  • 拼接后得到的模式是path\/to\/\!page|path\/to\/\!another,能正确匹配两个路径中的任意一个。

更简洁的写法

可以用preg_filter一次性完成数组元素的转义:

$url = 'example.com/path/to/!another';
$arr = ['path/to/!page', 'path/to/!another'];

$pattern = implode('|', preg_filter('/^/', '', $arr, PREG_QUOTE, '/'));

if(preg_match('/(' . $pattern . ')/', $url)) {
    echo 'The input url contains one of the paths in array!';
}

内容的提问来源于stack exchange,提问作者stckvrw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:35:25