PHP str_replace;检查更换部件以外的部件

PHP str_replace; check for more than the replace part

假设我有以下代码:

$string = "Hello! This is a test. Hello this is a test!"

echo str_replace("Hello", "Bye", $string);

这会将 $string 中的所有 Hello 替换为 Bye。我怎么能排除 Hello.

之后的所有 !

意思是,我想要这个输出:Hello! This is a test. Bye this is a test!

php 有办法做到这一点吗?

使用具有特定正则表达式模式的 preg_repalce 函数的解决方案:

$string = "Hello! This is a test. Hello this is a test!";
$result = preg_replace("/Hello(?!\!)/", "Bye", $string);

print_r($result);

输出:

Hello! This is a test. Bye this is a test!

(?!\!) - 前瞻性否定断言,匹配 Hello 单词仅当它后面没有'!'

您需要一个正则表达式:

echo preg_replace("/Hello([^!])/", "Bye", $string);

[] 是一个字符 class 而 ^ 表示 NOT。所以 Hello 后面没有 !。在 () 中捕获 Hello 之后的 NOT !,因此您可以在替换中将其用作 (第一个捕获组)。