我正在使用正则表达式来替换 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 bedistracted by the readable <br />content of a page when looking at its layou</p>那么有人可以建议在上面的正则表达式中需要进行哪些更改,以便如果 p 标签具有包含新行的字符串,它们可以正常工作?
2 回答
潇潇雨雨
TA贡献1833条经验 获得超4个赞
要使用 DOM 解析器,使用 DOMDocument 和loadHTML().
这会加载文档,然后用于getElementsByTagName()选择所有<p>标签。然后对于它找到的每个标签,它检查它是否具有属性并在需要时删除它们......
$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();
- 2 回答
- 0 关注
- 173 浏览
添加回答
举报
0/150
提交
取消