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

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

替換尚未替換的字符串

替換尚未替換的字符串

PHP
夢里花落0921 2021-12-03 15:43:12
所以我有這樣的文字:"word1 word2 word3 etc"我有一個帶有一組替換物的數組,我必須像這樣攜帶:[         "word1 word2" => "<a href="someurl">word1 word2</a>",     "word2"       => "<a href="someurl">word2</a>",     "word3"       => "<a href="someurl">word3</a>" ]基本上對于某些詞(或它們的組合),我必須添加一些標簽。我需要避免這種情況,因為“word1 word2”已經像這樣被替換了:<a href="someurl">word1 word2</a> word3 etc我需要避免它變成這樣:"<a href="someurl">word1 <a href="someurl">word2</a></a> word3 etc"                            ^^^ another replacement inside "word1 word2"如何避免替換已在其他替換中找到的較小字符串?使用 str_replace 的實時代碼不起作用:$array = [         "word1 word2" => "<a href='someurl'>word1 word2</a>",     "word2"       => "<a href='someurl'>word2</a>",     "word3"       => "<a href='someurl'>word3</a>" ];$txt = "word1 word2 word3 etc";echo str_replace(array_keys($array),array_values($array),$txt);http://sandbox.onlinephpfunctions.com/code/85fd62e88cd0131125ca7809976694ee4c975b6b正確的輸出:<a href="someurl">word1 word2</a> <a href="someurl">word3</a> etc
查看完整描述

3 回答

?
慕標琳琳

TA貢獻1830條經驗 獲得超9個贊

嘗試這個:


$array = [    

 "word1 word2" => "<a href='someurl'>word1 word2</a>",

 "word2"       => "<a href='someurl'>word2</a>",

 "word3"       => "<a href='someurl'>word3</a>" 

];


 $txt = "word1 word2 word3 etc";


foreach ($array as $word => $replacement) {

   if (!stripos($txt, ">$word<") && !stripos($txt, ">$word") && !stripos($txt, "$word<") ){

    $txt = str_replace($word, $replacement, $txt);

   }

}

echo $txt;


// output: <a href='someurl'>word1 word2</a> <a href='someurl'>word3</a> etc

基本上,在替換單詞之前,請檢查它是否已經包含在標簽中


查看完整回答
反對 回復 2021-12-03
?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

不確定這是否是最好的解決方案,但您可以將單詞的組合替換為完全不同的內容,然后在完成后將其替換回原來的形式。


例子


$array = [    

     "word1 word2" => "<a href='someurl'>***something***else***</a>",

     "word2"       => "<a href='someurl'>word2</a>",

     "word3"       => "<a href='someurl'>word3</a>",

];


$array2 = [    

     "***something***else***" => "word1 word2",

];


$txt = "word1 word2 word3 etc";

$txt = str_replace(array_keys($array),array_values($array),$txt);

$txt = str_replace(array_keys($array2),array_values($array2),$txt);


echo $txt;


查看完整回答
反對 回復 2021-12-03
?
蠱毒傳說

TA貢獻1895條經驗 獲得超3個贊

也許在一組替換數組的鍵上添加“空格”并執行str_replace()。可能是這樣的:


<?php

    //Enter your code here, enjoy!


    $array = [    

         "word1 word2 " => "<a href='someurl'>word1 word2</a>",

         "word2 "       => "<a href='someurl'>word2</a>",

         "word3 "       => "<a href='someurl'>word3</a>" 

    ];


    $txt = "word1 word2 word3 etc";


    echo str_replace(array_keys($array),array_values($array),$txt." ");


查看完整回答
反對 回復 2021-12-03
  • 3 回答
  • 0 關注
  • 253 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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