本文操作环境:windows7系统、php7.1版,dell g3电脑
具体问题:
php怎么实现单词替换?php字符串替换匹配整个单词
我想使用php替换完整的单词
例子 :
如果我有
$text = "hello hellol hello, helloz";
我用
$newtext = str_replace("hello",'new',$text);
新文本应如下所示
new hello1 hello, helloz
php返回
new hello1 hello, newz
实现方法:
您想使用正则表达式。 \b与单词边界匹配。
$text = preg_replace('/\bhello\b/', 'new', $text);
如果$text包含utf-8文本,则必须添加unicode修饰符“u”,以便不会将非拉丁字符误解为单词边界:
$text = preg_replace('/\bhello\b/u', 'new', $text);
推荐学习:《php视频教程》
以上就是php怎么实现单词替换的详细内容。
