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

2022-08-30 12:52:41

我想用php替换完整的单词

例 :如果我有

$text = "Hello hellol hello, Helloz";

我使用

$newtext = str_replace("Hello",'NEW',$text);

新文本应如下所示

新 你好1 你好, 你好

PHP 返回

新 你好1 你好, NEWz

谢谢。


答案 1

您希望使用正则表达式。匹配单词边界。\b

$text = preg_replace('/\bHello\b/', 'NEW', $text);

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

$text = preg_replace('/\bHello\b/u', 'NEW', $text);

答案 2

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

    $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.

推荐