负面展望未按预期工作

Negative look ahead not working as expected

我有一个奇怪的情况,正前瞻 按预期工作,但 负前瞻 没有。请看下面的代码:

<?php

$tweet = "RT @Startup_Collab: @RiseOfRest is headed to OMA & LNK to #showcase our emerging #startup ecosystem. Learn more! https://example.net #Riseof…";

$patterns=array(
    '/#\w+(?=…$)/',
);

$tweet = preg_replace_callback($patterns,function($m)
{
    switch($m[0][0])
    {
        case "#":
            return strtoupper($m[0]);
        break;
    }
},$tweet);


echo $tweet;

我想匹配任何没有跟随 …$ 和大写的标签(实际上它将用 href 解析出来,但为了简单起见,现在只是大写)。

这些是具有相应输出的正则表达式:

'/#\w+(?=…$)/' 匹配任何以 …$ 结尾的主题标签并将其大写,按预期工作:

RT @Startup_Collab: @RiseOfRest is headed to OMA & LNK to #showcase our emerging #startup ecosystem. Learn more! https://example.net #RISEOF…

'/#\w+(?!…$)/' 匹配任何不以 …$ 结尾的主题标签并将其大写,不起作用,所有主题标签都是大写的:

RT @Startup_Collab: @RiseOfRest is headed to OMA & LNK to #SHOWCASE our emerging #STARTUP ecosystem. Learn more! https://example.net #RISEOf…

非常感谢您的帮助、建议、想法和耐心。

--天使

那是因为回溯匹配了标签的一部分。使用所有格量词来避免回溯到 \w+ 子模式:

/#\w++(?!…$)/
    ^^

regex demo

现在,匹配了1个或多个字字符,(?!…$)否定先行只在这些字字符匹配后执行一次。如果出现false结果,则不发生回溯,整个匹配失败。

在此处查看有关 possessive quantifiers 的更多信息。