且构网

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

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

更新时间:2022-02-13 22:43:54

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

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

$text = preg_replace('/Hello/', '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('/Hello/u', 'NEW', $text);