不区分大小写,仅替换整个单词

发布于 2024-07-29 19:10:26 字数 336 浏览 2 评论 0 原文

我知道这真的很容易,而且我自己已经做过一百万次了; 但现在已经很晚了,我的大脑崩溃了。

我正在尝试匹配和替换整个单词而不是每次出现的单词。

所以,我想找到每一次出现的单词 me 并将其替换为 xxx ,这样 Me met smeg 就变成了 xxx met smeg 。 换句话说,Me遇见smeg不应该变成xxx xxxets sxxg

我知道它是 preg_match() 但我就是记不起整个单词的模式匹配。

I know this is really easy, and I've done it a million times myself; but it's late in the day and I have a brain meltdown.

I'm trying to match and replace whole words rather than every occurrence.

So, I want to find each occurrence of the word me and replace it with xxx so that Me meets smeg becomes xxx meets smeg. In other words, Me meets smeg should not become xxx xxxets sxxg.

I know it's preg_match() but I just can't remember the pattern matching for whole words.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

苏别ゝ 2024-08-05 19:10:26
$replaced = preg_replace('/\bme\b/i','xxx',$phrase);
$replaced = preg_replace('/\bme\b/i','xxx',$phrase);
无法言说的痛 2024-08-05 19:10:26

字边界字符

$output = preg_replace( "/\\bme\\b/", 'xxx', $input );

Word boundary characters

$output = preg_replace( "/\\bme\\b/", 'xxx', $input );
二智少女猫性小仙女 2024-08-05 19:10:26

\b 匹配单词边界,所以类似于 /\bMe\b/ (或 /\bme\b/i 不区分大小写)应该会给你你想要的正则表达式!

\b matches a word boundary, so something like /\bMe\b/ (or /\bme\b/i for case insensitivity) should give you the regex you desire!

娇俏 2024-08-05 19:10:26

您使用 \b 字边界。

$str = preg_replace('/\bMe\b/', 'xx', $str);

对于不区分大小写的情况,请使用 i 修饰符:

$str = preg_replace('/\bme\b/i', 'xx', $str);

You use the \b word boundary.

$str = preg_replace('/\bMe\b/', 'xx', $str);

For case insensitivity, use the i modifier:

$str = preg_replace('/\bme\b/i', 'xx', $str);
罪歌 2024-08-05 19:10:26

尝试以下正则表达式:

$replaced = preg_replace('/\bme\b/i', 'xxx', $subject);

\b单词边界。 Reference.backslash.php" rel="nofollow noreferrer">PCRE 参考

Try the following regex:

$replaced = preg_replace('/\bme\b/i', 'xxx', $subject);

\b is the word boundry as defined in the PCRE Reference.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文