使用正则表达式和 php 匹配未关闭的 html 标签 [英] Match unclosed html tags using regex and php

查看:42
本文介绍了使用正则表达式和 php 匹配未关闭的 html 标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 php 和 regex 在字符串中查找未关闭的 html 标签:

I am using php and regex to find unclosed html tags in a string :

这是我的字符串:

$s="<div><h2>Hello world<h2><p>It's 7Am where I live<p><div>";

你可以看到这里的所有标签都没有关闭.

You can see All tags here are not closed.

我想找到所有未闭合的标签,但问题是我的正则表达式也匹配开始标签.

I want to find all unclosed tags, but the problem is that my regex is matching opening tags also.

这是我目前的正则表达式

Here is my regex so far

/<[^>]+>/i

这是我的 preg_match_all() 函数

And this is my preg_match_all() function

preg_match_all("/<[^>]+>/i",$s,$v);

print_r($v);

我需要在我的正则表达式中更改什么以仅匹配未关闭的标签?

What do I need to change in my regex to match only the unclosed tags?

 <h2>
 <p>
 <div>

推荐答案

您可能不知道这一点,但 DOMDocument 可以帮助您修复 HTML.

You might be unaware of this, but DOMDocument can help you fix the HTML.

$html = "<div><h2>Hello world<h2><p>It's 7Am where I live<p><div>";
libxml_use_internal_errors(true);

$dom = new DOMDocument();
$dom->loadHTML('<root>' . $html . '</root>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);

foreach( $xpath->query('//*[not(node())]') as $node ) {
    $node->parentNode->removeChild($node);
}
echo substr($dom->saveHTML(), 6, -8);

参见 IDEONE 演示

结果:<div><h2>Hello world</h2><p>我住的地方现在是早上 7 点</p></div>

注意基于 XPath 的空节点清理是必要的,因为 DOM 包含空

,

Note that the XPath-based empty node cleanup is necessary as the DOM contains empty <h2></h2>, <p></p> and <div></div> tags after loading HTML into DOM.

元素是在开头添加的,以确保我们正确获取根元素.稍后,我们可以使用 substr 对其进行后处理.

The <root> element is added in the beginning to make sure we get the root element alright. Later, we can post-process it with substr.

LIBXML_HTML_NOIMPLIED |LIBXML_HTML_NODEFDTD 标志是必要的,这样就不会将 DTD 和其他垃圾添加到 DOM 中.

The LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD flags are necessary so that no DTD and other rubbish were not added to the DOM.

这篇关于使用正则表达式和 php 匹配未关闭的 html 标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆