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

PHP preg_match_all中含OR运算符的正则未捕获完整匹配问题

PHP preg_match_all 正则匹配结果不符问题解决

问题原因

你使用的正则表达式 /\bcredit\b|\bcredit note\b|\bfreddie\b 是按左到右顺序匹配分支的。当遇到包含credit note的字符串时,正则引擎会先匹配到单独的credit,匹配指针直接跳到credit之后的位置,导致完整的credit note没有机会被匹配,最终结果少了一项。

解决方法

调整正则分支顺序,把更长、更具体的匹配模式放在最前面,让引擎优先尝试匹配完整的长字符串:

$targetStr = <<<TEXT
last_name, first_name
bjorge, philip
sdfsdf credit note dfsdf
kardashian, kim
mercury, freddie
TEXT;

$regex = '/\bcredit note\b|\bcredit\b|\bfreddie\b/';
preg_match_all($regex, $targetStr, $result);

print_r($result);

执行结果

运行后得到的结果完全符合预期:

Array
(
    [0] => Array
        (
            [0] => credit
            [1] => credit note
            [2] => freddie
        )

)

可选优化(避免重复匹配)

如果不想在credit note字符串中同时匹配出credit和credit note,可以给credit添加负向预查,排除后面紧跟note的情况:

$regex = '/\bcredit note\b|\bcredit\b(?!\snote\b)|\bfreddie\b/';

这样只会匹配独立存在的credit,不会和credit note重复匹配同一位置的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:20:15