[英]PHP replace string with value from array
我正在嘗試用數組中的單詞替換字符串中的單詞。 問題是結果重復了多次。 我知道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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.