Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP字符串替换匹配整个单词_Php_String_Replace_Str Replace - Fatal编程技术网

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

PHP字符串替换匹配整个单词,php,string,replace,str-replace,Php,String,Replace,Str Replace,我想用php替换完整的单词 例如: 如果我有 $text = "Hello hellol hello, Helloz"; 我用 $newtext = str_replace("Hello",'NEW',$text); 新文本应该如下所示 你好,你好 PHP返回 你好,NEWz 谢谢。您想使用正则表达式。\b与单词边界匹配 $text = preg_replace('/\bHello\b/', 'NEW', $text); 如果$text包含UTF-8文本,则必须添加Unicode修饰符“

我想用php替换完整的单词

例如: 如果我有

$text = "Hello hellol hello, Helloz";
我用

$newtext = str_replace("Hello",'NEW',$text);
新文本应该如下所示

你好,你好

PHP返回

你好,NEWz


谢谢。

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

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

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

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

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

    $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.
$String=“团队成员致力于为所有买家和卖家提供优质服务。”;
echo$字符串;
回声“
”; $String=preg_replace(数组(“/\b团队\ b/”、“/\b团队\ b/”、“/\b团队\ b/”)、数组('Our'、'to'、'both')、$String); echo$字符串; 结果:我们的会员致力于为买家和卖家提供优质服务。
数组替换列表:如果替换字符串相互替换,则需要

显然,为了提高效率,
/\w+/
可以替换为键列表
/\b(一、二、三)b/i

您也可以使用库,在替换时引用
$
\
字符

<?php
$text = pattern('\bHello\b')->replace($text)->all()->with('NEW');

如果出现语法错误,请将最后一个大括号替换为
preg_replace
的括号。此外,
if(isset($pairs[$m[0]])
没有余弦括号。这与岳母匹配上述情况的修复方法可能在这里:
<?php
$text = pattern('\bHello\b')->replace($text)->all()->with('NEW');