Php preg_将标题替换为强标题

Php preg_将标题替换为强标题,php,regex,preg-replace,Php,Regex,Preg Replace,我试图用正则表达式替换文本中的所有标题(h1、h2、h3等),但它只替换第一个开始标记和最后一个 这是我的代码: <?php $regex = '/<h(?:[\d]{1})(?:[^>]*)>([^<].*)<\/h(?:[\d]{1})>/mi'; $str = '<h1 class="text-align-center" style="font-size:22px;margin-top:0px;margin-bottom:0px;color:

我试图用正则表达式替换文本中的所有标题(h1、h2、h3等),但它只替换第一个开始标记和最后一个

这是我的代码:

<?php
$regex = '/<h(?:[\d]{1})(?:[^>]*)>([^<].*)<\/h(?:[\d]{1})>/mi';
$str = '<h1 class="text-align-center" style="font-size:22px;margin-top:0px;margin-bottom:0px;color:rgb(0,0,0);font-family:IntroBold, sans-serif;line-height:1.5;letter-spacing:0px;font-weight:700;text-align:center;">You should be&nbsp;confident solving wicked problems in a hybrid role between strategy, research, design and business&nbsp;through a discovery driven approach.&nbsp;</h1><p></p><h2 style="margin-top:0px;margin-bottom:.5em;font-family:IntroBold, sans-serif;font-size:19px;line-height:1em;text-transform:uppercase;letter-spacing:1px;font-weight:700;"><strong>KEY RESPONSIBILITIES</strong></h2>';
echo preg_replace($regex, '<strong>$1</strong>', $str);

显然,regexp不是HTML解析的完美解决方案,如果您想要更安全的解决方案,您应该找到一个HTML解析器并以这种方式进行解析

但是,此regexp将完成一项相当不错的工作,并适用于提供的示例:

/(.*)/ims


.

您可以使用另一种替代方法

你可以用它做很多事情,包括你的关心

以下是您如何实现:

$dom = new simple_html_dom();
foreach($dom->find("h1,h2,h3,h4,h5") as $e)
            $e->outertext = "<strong>".$e->innertext."";
$dom=newsimple_html_dom();
foreach($dom->find(“h1、h2、h3、h4、h5”)作为$e)
$e->outertext=“”$e->innertext。”;
我正在用strong替换所有标题标签。

如果您愿意,您也可以使用内嵌css。

有一个更符合性能的路径来匹配标题:

<h(\d)[^>]*>([^<]*(<(?!\/h\1)[^<]*)*)<\/h\1>

不建议使用正则表达式进行html解析。使用html解析器提取值并将其放入新标记(如PHP internal DOMDocument)会更容易。请看一看,可能您正在寻找它,它适用于第一个标题,但第二个标题中没有内容。strong:Good catch,@Grork,我已使用修复程序更新了正则表达式。证明:这个正则表达式过于复杂
(?:[\d]{1})
可以是
\d
(?:.*)
可以是
*?
m
修饰符没有执行任何操作。
$dom = new domdocument();
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new domxpath($dom);
$headings = $xpath->query("//h1 | //h2 | //h3 | //h4 | //h5 | //h6");
foreach ($headings as $h) {
    $s = $dom->createElement("strong", $h->nodeValue);
    $h->parentNode->replaceChild($s, $h);
}
echo $dom->saveHTML();