【发布时间】:2011-12-22 03:50:39
【问题描述】:
我正在开发一个包含词汇表的网站,其中解释了一些单词。 另外,我想通过将它们放在具有标题属性的跨度中来描述文章中的术语。
我从一个数组中的数据库中获取所有术语:
$terms = array(
'word1' => 'This is a short description of word1',
'word2' => 'word2 maybe has something to do with word1'
);
包含文本的字符串可以是:
$string = 'In this sentence I want to explain both, word1 and word2.';
我尝试用简单的 str_ireplace() 替换字符串中包含的单词:
foreach($terms as $term => $description)
{
$string = str_ireplace($term, '<span class="help" title="' . $description . '">' . $term . '</span>', $string);
}
现在发生的是,word1 和 word2 被正确替换。但是通过第二次迭代文本来搜索和替换 word2,它再次找到 word1 - 在已经创建的 span 的标题中。
所以 word1 的结果应该是这样的:
<span class="help" title="This is a short description of <span class="help" title="This is a short description of word1">word1</span>word1</span>
如何防止 PHP 替换现有跨度的标题标签中的相同单词?我不想为此使用 preg_replace() ,而不是将 html 解析为它。
我该怎么做?
来自德国的可爱问候 克里斯
【问题讨论】:
标签: php replace words glossary