我想在标题中替换“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>");
});
});
});
答案 0 :(得分: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>
答案 1 :(得分: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 ;
答案 2 :(得分:1)
使用regexp非常简单,此示例仅使用一个关键字,因为多个关键字使用数组。
$string = "<h2>This is the heading</h2>";
$string = preg_replace("/(the|end)/", "<span>$1</span>", $string);