当一个单词本身是或isn't时,使用str_replace将该单词替换为none


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"左右的空格,因为如果那个单词是另一个单词的一部分怎么办?然后它就会替换掉它,然后它就错了。

EDIT我改编了str_replace示例并添加了regex示例


与<<p> strong> str_replace (不推荐)
str_replace(array(" replace "," replace ","  "),array(" "," "," "))

检查http://php.net/manual/en/function.str-replace.php如果语法错误,但我认为我记得它是正确的。

但是,这对于编码来说很尴尬,并且不是在所有情况下都可以复制。


正则表达式与

建议: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);