Php html标记中新行的正则表达式

Php html标记中新行的正则表达式,php,regex,Php,Regex,如果具有html属性的p标记没有属性,并且正则表达式是: $html = preg_replace("/<p[^>]*>(.+?)<\/p>/i", "<p>$1</p>", $html); $html=preg_replace(“/]*>(.+?)/i“,“$1”,$html); 如果p标记没有任何新行,则Regex工作正常 <p style="text-align: center;">It is a long establ

如果具有html属性的p标记没有属性,并且正则表达式是:

$html = preg_replace("/<p[^>]*>(.+?)<\/p>/i", "<p>$1</p>", $html);
$html=preg_replace(“/]*>(.+?)/i“,“$1

”,$html);
如果p标记没有任何新行,则Regex工作正常

<p style="text-align: center;">It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout</p>

读者在查看页面布局时会被页面的可读内容分散注意力,这是一个早已确定的事实

但当p标记有新行时,上面的正则表达式就不起作用了。例如

<p style="text-align: center;">It is a long established fact that a reader will be
distracted by the readable <br />
content of a page when looking at its layou</p>
读取器将是一个长期存在的事实 被可读的内容分散注意力
查看页面布局时的页面内容


那么,有人能建议在上面的正则表达式中需要做哪些更改,以便在p标记有包含新行的字符串时正常工作吗?

如果您必须,请使用

$html = preg_replace("/<p[^>]*>(.+?)<\/p>/is", "<p>$1</p>", $html);
#                                          ^
$html=preg_replace(“/]*>(.+?)/is“,“$1

”,$html); # ^
这将启用
单行
模式,也就是点匹配换行符。不过,通常的警告是不要在
HTML
标记上使用正则表达式。

请参阅。

要使用DOM解析器,使用DOMDocument和
loadHTML()
非常简单

这将加载文档,然后使用
getElementsByTagName()
选择所有
标记。然后,对于找到的每个标记,它检查是否有属性,并在需要时删除它们

$doc = new DOMDocument();
$doc->loadHTML($html);

$pTags = $doc->getElementsByTagName("p");
foreach ( $pTags as $p )    {
    if ( $p->hasAttributes() )  {
        foreach ( $p->attributes as $attribute )    {
            $p->removeAttribute($attribute->nodeName );
        }
    }
}

// Save/echo the resultant HTML
echo $doc->saveHTML();

最好不要为此使用正则表达式@当然,谢谢你的建议,我以后也会这么做的。