html标签中新行的正则表达式

我正在使用正则表达式来替换 p 标签,如果有 p 标签没有属性的 html 属性和正则表达式是:


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

如果 p 标签没有任何新行,则正则表达式运行良好


<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 标签具有包含新行的字符串,它们可以正常工作?


Cats萌萌
浏览 174回答 2
2回答

潇潇雨雨

要使用 DOM 解析器,使用 DOMDocument 和loadHTML().这会加载文档,然后用于getElementsByTagName()选择所有<p>标签。然后对于它找到的每个标签,它检查它是否具有属性并在需要时删除它们......$doc = new DOMDocument();$doc->loadHTML($html);$pTags = $doc->getElementsByTagName("p");foreach ( $pTags as $p )&nbsp; &nbsp; {&nbsp; &nbsp; if ( $p->hasAttributes() )&nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; foreach ( $p->attributes as $attribute )&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $p->removeAttribute($attribute->nodeName );&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}// Save/echo the resultant HTMLecho $doc->saveHTML();
打开App,查看更多内容
随时随地看视频慕课网APP