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
基本上,在替换单词之前,请检查它是否已经包含在标签中
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;
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." ");
- 3 回答
- 0 关注
- 224 浏览
添加回答
举报