猿问

替换尚未替换的字符串

所以我有这样的文字:


"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


梦里花落0921
浏览 230回答 3
3回答

慕标琳琳

尝试这个:$array = [&nbsp; &nbsp;&nbsp;&nbsp;"word1 word2" => "<a href='someurl'>word1 word2</a>",&nbsp;"word2"&nbsp; &nbsp; &nbsp; &nbsp;=> "<a href='someurl'>word2</a>",&nbsp;"word3"&nbsp; &nbsp; &nbsp; &nbsp;=> "<a href='someurl'>word3</a>"&nbsp;];&nbsp;$txt = "word1 word2 word3 etc";foreach ($array as $word => $replacement) {&nbsp; &nbsp;if (!stripos($txt, ">$word<") && !stripos($txt, ">$word") && !stripos($txt, "$word<") ){&nbsp; &nbsp; $txt = str_replace($word, $replacement, $txt);&nbsp; &nbsp;}}echo $txt;// output: <a href='someurl'>word1 word2</a> <a href='someurl'>word3</a> etc基本上,在替换单词之前,请检查它是否已经包含在标签中

动漫人物

不确定这是否是最好的解决方案,但您可以将单词的组合替换为完全不同的内容,然后在完成后将其替换回原来的形式。例子$array = [&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp;"word1 word2" => "<a href='someurl'>***something***else***</a>",&nbsp; &nbsp; &nbsp;"word2"&nbsp; &nbsp; &nbsp; &nbsp;=> "<a href='someurl'>word2</a>",&nbsp; &nbsp; &nbsp;"word3"&nbsp; &nbsp; &nbsp; &nbsp;=> "<a href='someurl'>word3</a>",];$array2 = [&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp;"***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;

蛊毒传说

也许在一组替换数组的键上添加“空格”并执行str_replace()。可能是这样的:<?php&nbsp; &nbsp; //Enter your code here, enjoy!&nbsp; &nbsp; $array = [&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"word1 word2 " => "<a href='someurl'>word1 word2</a>",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"word2 "&nbsp; &nbsp; &nbsp; &nbsp;=> "<a href='someurl'>word2</a>",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"word3 "&nbsp; &nbsp; &nbsp; &nbsp;=> "<a href='someurl'>word3</a>"&nbsp;&nbsp; &nbsp; ];&nbsp; &nbsp; $txt = "word1 word2 word3 etc";&nbsp; &nbsp; echo str_replace(array_keys($array),array_values($array),$txt." ");
随时随地看视频慕课网APP
我要回答