将标题中的关键字替换为php或jquery


Replace keyword in a heading with php or jquery?

我想替换标题中的关键字,如"the"、"and"等,并在标题标记中用span替换。

例如:

<h2>This is the heading</h2>

成为

<h2>This is <span>the</span> heading</h2>

感谢的帮助

更新

我找到了一个能满足我需求的东西:

$(function() {
$('h2').each(function(i, elem) {
    $(elem).html(function(i, html) {
        return html.replace(/the/, "<span>the</span>");
    });
});
});

仅限PHP的解决方案(不含正则表达式):

$string = "<h2>This is the heading</h2>";
$toReplace = array("the", "and");
$replaceTo = array_map(function ($val) { return "<span>$val</span>"; }, $toReplace);
$newString = str_replace($toReplace, $replaceTo, $string);
print $newString; // prints as expected: <h2>This is <span>the</span> heading</h2>

这段代码将帮助您做到这一点,并动态扩展您的单词:

$special_words = array("the", "and", "or") ;
$words = implode("|", $special_words) ;
$string = "<h2>This is the heading</h2>" ;
$new = preg_replace("/({$words})/i", "<span>$1</span>", $string) ;
echo $new ;

使用regexp非常简单,这个例子只使用一个关键字,对于多个关键字使用一个数组。

$string = "<h2>This is the heading</h2>";
$string = preg_replace("/(the|end)/", "<span>$1</span>", $string);