我们是新的PHP中的正则表达式(的preg_replace),并有一个小麻烦得到它做的正是我们想要的。
我们有,例如,HTML代码如下所示:
<h2><strong>Automatic Writing</strong> <strong>– A Conduit For An Entity From Another World?</strong></h2>
我们要删除所有样式标签H2内(甚至太匹配H3 / H4 / H5标签)。
我们已经构建了下面的代码至今(我们正在与WordPress的集成):
function removebolding($content)
{
$content =
preg_replace('/(<h([1-6])[^>]*>)\s?<strong>(.*)?<\/strong>\s?(<\/h\2>)/', "$1$3$4", $content);
return $content;
}
add_filter('the_content', 'removebolding');
这并不工作,但它只是删除了第一个“强”的标签 - 我们只剩下:
<h2>Automatic Writing <strong>– A Conduit For An Entity From Another World?</strong></h2>
我们怎样才能匹配/删除所有“强”的标签?此外,也许我们可以简单地提取标题标签的内容,运行strip_tags的功能,然后用输出替换?
任何帮助,建议和代码示例提前衷心感谢。
非常感谢。
您可以使用
preg_replace_callback('~<h([1-6])>.*?</h\1>~is', function($m) {
return preg_replace('~</?strong>~i', '', $m[0]); }
, $s)
输出:<h2>Automatic Writing – A Conduit For An Entity From Another World?</h2>
正则表达式的性能,可以增强这样的:
'~<h([1-6])>[^<]*(?:<(?!/h\1>[^<]*)*</h\1>~i'
见PHP demo。
~<h([1-6])>.*?</h\1>~s
匹配任何h
标签,用任何文本在它们之间preg_replace('~</?strong>~i', '', $m[0])
删除所有<strong>
和</strong>
标签仅适用于主正则表达式匹配值,在$m[0]
。