亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

PHP
LEATH 2021-11-26 15:56:58
我正在嘗試用數組中的單詞替換字符串中的單詞。問題是結果重復多次。我知道 有一個問題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;

工作演示。


查看完整回答
反對 回復 2021-11-26
  • 1 回答
  • 0 關注
  • 244 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號