-2

我想替换标题中的“the”、“and”等关键字,并将其替换为标题标签中的跨度。

前任:

<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>");
    });
});
});
4

3 回答 3

3

仅 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>
于 2013-06-30T13:48:41.680 回答
1

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

$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 ;
于 2013-06-30T13:47:43.930 回答
1

使用正则表达式很容易,这个例子只使用一个关键字,多个关键字使用一个数组。

$string = "<h2>This is the heading</h2>";
$string = preg_replace("/(the|end)/", "<span>$1</span>", $string);
于 2013-06-30T13:48:08.007 回答