在具有特定类的 span 标记中嵌入字符串


Embed string in a span tag with certain class

>我有一个字符串,我想在其中突出显示单词"some":

$my_string = "This is some string.";
$highlight = "some";

我需要使用一些最适合这项工作的 php 函数将这个词包装在 <span> 标签中。

我正在使用它在我的网站上进行简单搜索。

所以,我希望最终结果看起来像这样:

This is <span class="highlight-word">some</span> string.
您可以使用

注释中提到的str_replace。因此,在您的情况下,它看起来像这样:

$my_string = "This is some string.";
$highlight = "some";
echo str_replace($highlight, sprintf('<span class="highlight-word">%s</span>', $highlight), $my_string);
// This is <span class="highlight-word">some</span> string.

首先,你不应该突出显示具有这种跨度的单词。有一些HTML元素专门设计用于查看em和strong以获取有关如何使用它们的信息。

实现所需目标的最佳选择是将 PHP str_replace包装在包装器函数中,因为您可能希望在多个位置执行此操作。

function setStrong($wordToStrong, $sentence)
{
    $strong = "<strong>$wordToStrong</strong>";
    return str_replace($wordToStrong, $strong, $sentence);
}

然后像这样使用:-

echo setStrong("strong", "This should be a strong word");