且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-02 22:28:51

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

You want to use regular expressions. The \b matches a word boundary.

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


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


If $text contains UTF-8 text, you'll have to add the Unicode modifier "u", so that non-latin characters are not misinterpreted as word boundaries:

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