PHP str_replace with array() 获取嵌套覆盖替换值

PHP str_replace with array() gets nested overwriting replaced values

我想用文本中的标记词替换词。

tbl_glossary
id  word
1   apple pie
2   apple
3   juice

这些词在数据库 (MySQL) 的数组中。如果单词包含相同的值(例如 'apple pie' 包含 'apple'),则单词将被替换为替换的单词。

$con = mysqli_connect(db_host, db_username, db_password, db_name);
$sql = "SELECT * FROM `tbl_glossary`";
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($res)){
    $arr_taggedword[] = '<a href="#" data-toggle="tooltip" id="'.$row['id'].'">'.$row['word'].'</a>';
    $arr_word[] = $row['word'];
}

$text = "apple pie made with apple juice";

$results = $text;
foreach($arr_word as $key => $value) {
    $results = str_replace($value, $arr_taggedword[$key], $results);
}
echo $results;

则结果显示为

<a href="#" data-toggle="tooltip" id="1"><a href="#" data-toggle="tooltip" id="2">apple</a> pie</a> made with <a href="#" data-toggle="tooltip" id="2">apple</a> <a href="#" data-toggle="tooltip" id="3">juice</a>

'apple pie' 是嵌套的。 想 skip/ignore 替换单词以再次替换吗?

提前致谢。

您可以使用strtr的数组形式,它会按照从大到小的顺序进行所有替换,但不会替换任何已经被替换的文本。将 foreach 循环替换为:

$results = strtr($text, array_combine($arr_word, $arr_taggedword));
echo $results;

输出

<a href="#" data-toggle="tooltip" id="1">apple pie</a> made with <a href="#" data-toggle="tooltip" id="2">apple</a> <a href="#" data-toggle="tooltip" id="3">juice</a>