我正在嘗試用數組中的單詞替換字符串中的單詞。問題是結果重復多次。我知道 有一個問題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.
1 回答

倚天杖
TA貢獻1828條經驗 獲得超3個贊
使用替換模式作為數組,它首先轉換{Amir|Mahdi} and Mahdi are friends.,再次對于數組的第二個索引,Mahdi它同時轉換兩者Mahdi。這就是為什么我建議您在模式而不是數組中使用|( OR ) 條件。
$text = 'Amir and Mahdi are friends.';
$text2 = preg_replace("/Amir|Mahdi/", '{Amir|Mahdi}', $text);
echo $text2;
工作演示。
- 1 回答
- 0 關注
- 244 瀏覽
添加回答
舉報
0/150
提交
取消