当一个词是或不是它自己时用 str_replace 替换一个词

Replacing a word with nothing when that word is or isn't by itself with str_replace

我试图用空替换字符串中的某个单词,但我遇到了一个问题。如果那个特定的词紧挨着它自己,它不会替换。我该如何解决?谢谢。

$text1 = "text replace text replace text";
$text1 = str_replace(" replace "," ",$text1);

$text2 = "text replace replace text";
$text2 = str_replace(" replace "," ",$text2);

echo $text1;
echo $text2;

实际结果

text text text
text replace text

预期结果

text text text
text text

P.S:我也不想做像 str_replace("replace"," ",$text2) 这样的事情,在 "replace" 取消,因为如果那个词是另一个词的一部分怎么办?那它无论如何都会替换它,它会出错。

编辑 根据评论我调整了我的 str_replace 示例并添加了正则表达式示例


搭配str_replace(不推荐)

str_replace(array(" replace "," replace ","  "),array(" "," "," "))

检查 http://php.net/manual/en/function.str-replace.php 如果语法错误,但我想我没记错。

但是,这对编码来说很笨拙,而且并非在所有情况下都可以复制。


使用 regex

大概要走的路:http://php.net/manual/en/function.preg-replace.php

我很生疏,但这应该行得通:

$ret = 'test replace test replace replace dontreplace test';
$pattern = '/\breplace\b/i';
$ret = preg_replace($pattern,"",$ret);
var_dump($ret);

这个正则表达式应该可以工作,也许需要一些调整:

$word = 'someWordToReplace';  
$resultString = preg_replace('/(?:(?<= )|(?<=\A))'.$word.'(?:(?= )|(?=\Z))/', '', $str);