str_replace:仅匹配整个单词 [英] str_replace: Match whole word only

查看:47
本文介绍了str_replace:仅匹配整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 str_replace() 在 ":Name :Name_en" 中匹配 ":Name" 两次,所以我只想匹配整个单词的结果.我想切换到 preg_replace() 因为这个答案.

Since str_replace() matches ":Name" two times in ":Name :Name_en" I want to match the results for the whole word only. I wanted to switch to preg_replace() because of this answer.

$str = ":Name :Name_en";
echo $str . chr(10);
$str = preg_replace('/\b' . ':Name' . '\b/i', '"Test"', $str);
echo $str;

但是由于冒号,这不起作用.不进行更换.RegExp 会是什么样子?

But this doesn't work because of the colon. No replacement takes place. How would the RegExp will look like?

\b 是单词边界.但我认为冒号不属于这样的词边界.

\b is the word boundary. But I think a colon doesn't belong to such a word boundary.

推荐答案

您不需要字符串开头的单词边界:

You don't need the word boundary on the start of your string:

$str = preg_replace('/:Name\b/i', '"Test"', $str);

这篇关于str_replace:仅匹配整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆