使用 PHP 用标题范围包裹单词
我正在开发一个包含术语表的网站,其中解释了一些单词。 另外,我想通过将文章中的术语放在带有标题属性的跨度中来描述它们。
我从数据库中获取数组中的所有术语:
$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 - 在已创建的范围的标题中。
因此,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 。
我怎么能这么做呢?
来自德国的可爱问候 克里斯
i'm working on a website that includes a glossary, in which a few words are explained.
Additionaly I want to describe the terms in an article by putting them in spans with a title attribute.
I get all the terms from the database in an array:
$terms = array(
'word1' => 'This is a short description of word1',
'word2' => 'word2 maybe has something to do with word1'
);
The String containing the text could be:
$string = 'In this sentence I want to explain both, word1 and word2.';
I tried to simply replace the words contained in the string by a simple str_ireplace():
foreach($terms as $term => $description)
{
$string = str_ireplace($term, '<span class="help" title="' . $description . '">' . $term . '</span>', $string);
}
What happens now is, that word1 and word2 is replaced correctly. But by iterating a second time over the text to search and replace word2, it finds word1 again - in the title of the already created span.
So the result for word1 would look like this:
<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>
How could I prevent PHP from replacing the same word in the title tag of an existing span? I wouldn't like to use preg_replace() for that, to not parse html to it.
How could I do that?
Lovely Greets from germany
Chris
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
strtr
来实现:请参阅 http://codepad.org/VEBLQcBe 了解一个工作示例
strtr
将翻译字符或替换子字符串You can use
strtr
for that:See http://codepad.org/VEBLQcBe for a working example
strtr
will translate characters or replace substrings