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



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

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>

"苹果派"是嵌套的。想跳过/忽略被替换的单词以再次被替换吗?

提前谢谢。

您可以使用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>

最新更新