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

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

php str_replace() 搜索中的重復詞

php str_replace() 搜索中的重復詞

PHP
精慕HU 2023-04-02 11:16:24
嘗試使用搜索和替換一些內容str_replace()。如果 the 是唯一的,它工作正常$find,但是一旦$find有重復的單詞,整個事情就搞砸了。例如 The style1will be applyed on both$find[0] && $find[1]因為兩者都是Lorem Ipsum,同樣適用于dummy。如何處理這種情況?$find = Array(    [0] => Lorem Ipsum     [1] => Lorem Ipsum     [2] => typesetting     [3] => dummy     [4] => dummy );$replace = Array(    [0] => style1    [1] => style2    [2] => style3    [3] => style4    [4] => style5);$string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.            Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,            when an unknown printer took a galley of type and scrambled it to make a type specimen book.";$result = str_replace($find,$replace,$string);echo $result;
查看完整描述

1 回答

?
HUX布斯

TA貢獻1876條經驗 獲得超6個贊

您可以使用此問題str_replace_first中描述的實現,并迭代您的和數組,僅替換數組中每個值的一次出現:$find$replace$find


function str_replace_first($search, $replace, $subject) {

? ? if (($pos = strpos($subject, $search)) !== false) {

? ? ? ? return substr_replace($subject, $replace, $pos, strlen($search));

? ? }

? ? return $subject;

}


$result = $string;

foreach ($find as $key => $search) {

? ? $result = str_replace_first($search, $replace[$key], $result);

}

echo $result;

輸出:


style1 is simply style4 text of the printing and style3 industry.?

style2 has been the industry's standard style5 text ever since the 1500s,?

when an unknown printer took a galley of type and scrambled it to make a type specimen book.



查看完整回答
反對 回復 2023-04-02
  • 1 回答
  • 0 關注
  • 156 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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