php - 去除 PHP 中所有空的 HTML 标记对

标签 php html regex

我正在寻找一种方法来去除所有空的 HTML 标记对,例如字符串中的 <strong></strong><p class="bold"></p>。虽然为此目的找到正则表达式相对容易,但我找不到可以可靠地与 PHP 的 preg_replace() 一起工作的正则表达式。这是我尝试过的功能之一(取自 https://stackoverflow.com/a/5573115/1784564 ):

function strip_empty_tags($text) {
    // Match empty elements (attribute values may have angle brackets).
    $re = '%
        # Regex to match an empty HTML 4.01 Transitional element.
        <                    # Opening tag opening "<" delimiter.
        ((?!iframe)\w+)\b    # $1 Tag name.
        (?:                  # Non-capture group for optional attribute(s).
          \s+                # Attributes must be separated by whitespace.
          [\w\-.:]+          # Attribute name is required for attr=value pair.
          (?:                # Non-capture group for optional attribute value.
            \s*=\s*          # Name and value separated by "=" and optional ws.
            (?:              # Non-capture group for attrib value alternatives.
              "[^"]*"        # Double quoted string.
            | \'[^\']*\'     # Single quoted string.
            | [\w\-.:]+      # Non-quoted attrib value can be A-Z0-9-._:
            )                # End of attribute value alternatives.
          )?                 # Attribute value is optional.
        )*                   # Allow zero or more attribute=value pairs
        \s*                  # Whitespace is allowed before closing delimiter.
        >                    # Opening tag closing ">" delimiter.
        \s*                  # Content is zero or more whitespace.
        </\1\s*>             # Element closing tag.
        %x';
    while (preg_match($re, $text)) {
        // Recursively remove innermost empty elements.
        $text = preg_replace($re, '', $text);
    }

    return $text;
}

这是我一直在测试的 HTML:

<strong class="a b">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.l<br class="a  b" />fd<br class="a  b" /><br class="a  b" /></strong><strong class="a b"></strong><strong class="a b"><br class="a  b" /></strong><strong class="a b"></strong><br class="a  b" /><strong class="a b"><br class="a  b" /><br class="a  b" /></strong>

到目前为止,我尝试过的所有方法(已经尝试了 4 个多小时)似乎都去除了一些标签,但不是所有标签,这让我抓狂。任何帮助将不胜感激。

最佳答案

需要一个 unicode regex因为示例“空”标签实际上是 not empty :

$re = '~<(\w+)[^>]*>[\p{Z}\p{C}]*</\1>~u';

\p{Z} ...任何类型的空格或不可见的分隔符
\p{C} ...不可见的控制字符和未使用的代码点

二手 u (PCRE_UTF8) modifier ; test at regex101


还包括 <br> , <br />作为空元素:

$re = '~<(\w+)[^>]*>(?>[\p{Z}\p{C}]|<br\b[^>]*>)*</\1>~ui';

test at regex 101


同时将标签与空间实体匹配

$re = '~<(\w+)[^>]*>(?>[\p{Z}\p{C}]|<br\b[^>]*>|&(?:(?:nb|thin|zwnb|e[nm])sp|zwnj|#xfeff|#xa0|#160|#65279);)*</\1>~iu'

test at regex101 ;根据您的需要进行修改。


使用 recursive regex (没有 while 循环)

$re = '~<(\w+)[^>]*>(?>[\p{Z}\p{C}]|<br\b[^>]*>|&(?:(?:nb|thin|zwnb|e[nm])sp|zwnj|#xfeff|#xa0|#160|#65279);|(?R))*</\1>~iu';

test at regex101

关于php - 去除 PHP 中所有空的 HTML 标记对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25748002/

相关文章:

php - 更新foreach中的数据

python - 排除 ".txt"个文件

php - 如何更改 WordPress 页面上的标题?

php - 在 php 中用正则表达式替换短代码

html - 动画在 mozilla 中不起作用

javascript - 使用regexp javascript从源文件中查找所有导入的文件名

javascript - 如何将负向后查找与未知字符相匹配?

php - 以数据库base64格式存储的图像如何在PHP中以原始格式检索它

php - 当 XML 包含 namespace 时如何将 XPath 与 PHP 一起使用

html - https 是否保留在相对表单操作 URL 上?