PHP用数组中的值替换字符串

时间:2019-08-16 11:20:33

标签: php

我正在尝试用数组中的单词替换字符串中的单词。问题是结果重复了多次。我知道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.

1 个答案:

答案 0 :(得分:1)

使用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;

工作demo