簡體   English   中英

PHP用數組中的值替換字符串

[英]PHP replace string with value from array

我正在嘗試用數組中的單詞替換字符串中的單詞。 問題是結果重復了多次。 我知道str_replace有一個陷阱,但是我找不到這個問題的任何解決方案。

我嘗試了str_replacepreg_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.

用replace patter作為數組,它首先將{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;

工作演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM