首页 > 解决方案 > 负前瞻与预期不匹配

问题描述

我正在尝试使用preg_replace(). 我需要检查这个词后面是否没有任何这个 set [a-zA-Z0-9_$.]。为了实现这一点,我使用了否定的lookahead,例如,如果目标词是"foo"并且我有一个字符串,例如:

"hello_foo this foo is an example.foo"

...我想foobar这个正则表达式替换

$old = "hello_foo this foo is an example.foo";

$new = preg_replace("/(?![a-zA-Z0-9_$.])foo/", "bar" $old); 

...这应该返回

"hello_foo this bar is an example.foo"

这没有按预期工作。但是,如果我a-z从正则表达式中删除该集合,它确实可以工作,但现在它会将这样的单词替换"aaafoo""aaabar".

我在这里错过了什么吗?我是正则表达式的新手。

标签: phpregexregex-lookarounds

解决方案


推荐阅读