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 關注
- 253 瀏覽
添加回答
舉報