替换尚未替换的字符串

时间:2019-08-23 08:21:14

标签: php

所以我有这样的文字:

"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"

如何避免在其他替换项中已经找到较小字符串的replacemnet?

使用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 个答案:

答案 0 :(得分:1)

尝试一下:

$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

基本上,在替换单词之前,请检查单词是否已包装在标签中

答案 1 :(得分:0)

不确定这是否是最好的解决方案,但您可以将单词的组合替换为完全不同的内容,然后在完成后将其替换回其原始形式。

示例

$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;

答案 2 :(得分:0)

可能在替换数组集的键处添加“空格”,然后执行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." ");