PHP字符串替换匹配整个单词

NVG*_*NVG 31 php string replace str-replace

我想用php替换完整的单词

示例:如果有的话

$text = "Hello hellol hello, Helloz";
Run Code Online (Sandbox Code Playgroud)

我用

$newtext = str_replace("Hello",'NEW',$text);
Run Code Online (Sandbox Code Playgroud)

新文本看起来应该是这样的

新hello1你好,Helloz

PHP返回

NEW hello1你好,NEWz

谢谢.

Let*_*rgy 60

您想使用正则表达式.该\b单词边界匹配.

$text = preg_replace('/\bHello\b/', 'NEW', $text);
Run Code Online (Sandbox Code Playgroud)

如果$text包含UTF-8文本,则必须添加Unicode修饰符"u",以便非拉丁字符不会被误解为字边界:

$text = preg_replace('/\bHello\b/u', 'NEW', $text);
Run Code Online (Sandbox Code Playgroud)

  • 这和婆婆的妈妈很配 (2认同)

san*_*mar 6

字符串中的多个单词替换为此

    $String = 'Team Members are committed to delivering quality service for all buyers and sellers.';
    echo $String;
    echo "<br>";
    $String = preg_replace(array('/\bTeam\b/','/\bfor\b/','/\ball\b/'),array('Our','to','both'),$String);
    echo $String;
    Result: Our Members are committed to delivering quality service to both buyers and sellers.
Run Code Online (Sandbox Code Playgroud)