【问题标题】:Wrapping words with a titled span with PHP用 PHP 用带标题的 span 包装单词
【发布时间】: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


    【解决方案1】:

    您可以为此使用strtr

    $string = 'In this sentence I want to explain both, word1 and word2.';
    $terms = array(
        'word1' => '<span title="This is a short description of word1">word1</span>',
        'word2' => '<span title="word2 maybe has something to do with word1">word1</span>',
    );
    echo strtr($string, $terms);
    

    这句话我想同时解释一下,word1word1有关。

    有关工作示例,请参阅 http://codepad.org/VEBLQcBe

    strtr 将翻译字符或替换子字符串

    【讨论】:

    • 哦,伙计,我一直在寻找一个星期的解决方案.. :/ 非常感谢!但是 strtr 是区分大小写的,不是吗?有什么方法或替代方法可以让它不区分大小写?
    • @chris.ribal 如果您查看 strtr 手册页的 cmets 部分,则有一些 stritr 实现。
    猜你喜欢
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多