我正在尝试用数组中的单词替换字符串中的单词。问题是结果重复了多次。我知道str_replace
有一个陷阱,但是我找不到这个问题的解决方案。
我尝试使用str_replace
和preg_replace
。
使用str_replace
:
$text = 'Amir and Mahdi are friends.';
$text2 = str_replace(array("Amir","Mahdi"), '{Amir|Mahdi}', $text);
结果:{Amir|{Amir|Mahdi}} and {Amir|Mahdi} are friends.
使用preg_replace
:
$text = 'Amir and Mahdi are friends.';
$text2 = preg_replace(array("/Amir/","/Mahdi/"), '{Amir|Mahdi}', $text);
结果:{Amir|{Amir|Mahdi}} and {Amir|Mahdi} are friends.
我想要这个结果:{Amir|Mahdi} and {Amir|Mahdi} are friends.