【问题标题】:Remove not closed html elements from end of text从文本末尾删除未关闭的 html 元素
【发布时间】:2013-08-11 05:28:14
【问题描述】:

我想删除所有在内容末尾没有正确关闭的元素,例如在下面的测试中

commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea
voluptate velit esse quam nihil molestiae consequatur, 
vel illum qui dolorem eum fugiat quo voluptas nulla 
pariatur? <a rel="nofollow" class="underline"

我要删除

<a rel="nofollow" class="underline"

或没有结束标签的元素

<h2>sample text

或任何其他最后没有正确关闭的html元素。

【问题讨论】:

  • 您只是想完全删除它们,还是修复它们?
  • 我只是想从文本末尾删除损坏的 html 元素,而不是全部
  • @nyzm 提到 url 使用插件,我想尽可能避免使用插件
  • 你可以通过codepad.org/EupocXQR 做到这一点,但我不支持这个想法

标签: php html regex


【解决方案1】:

我已经编写了一个函数,它应该可以满足您的需求。这个想法是首先用#### 模式替换所有有效的标签序列。然后正则表达式删除从第一个 &lt; 到字符串末尾的所有内容。之后,有效的标签序列被放回缓冲区(如果该部分由于该部分之前的无效标签而未被删除)。

太糟糕了,我无法添加键盘,因为递归正则表达式似乎不受键盘使用的 PHP 版本的支持。我已经用 PHP 5.3.5 对此进行了测试。

PHP

function StripUnclosedTags($input) {
    // Close <br> tags
    $buffer = str_ireplace("<br>", "<br/>", $input);
    // Find all matching open/close HTML tags (using recursion)
    $pattern = "/<([\w]+)([^>]*?) (([\s]*\/>)| (>((([^<]*?|<\!\-\-.*?\-\->)| (?R))*)<\/\\1[\s]*>))/ixsm";
    preg_match_all($pattern, $buffer, $matches, PREG_OFFSET_CAPTURE);
    // Mask matching open/close tag sequences in the buffer
    foreach ($matches[0] as $match) {
        $ofs = $match[1];
        for ($i = 0; $i < strlen($match[0]); $i++, $ofs++)
            $buffer[$ofs] = "#";
    }
    // Remove unclosed tags
    $buffer = preg_replace("/<.*$/", "", $buffer);
    // Put back content of matching open/close tag sequences to the buffer
    foreach ($matches[0] as $match) {
        $ofs = $match[1];
        for ($i = 0; $i < strlen($match[0]) && $ofs < strlen($buffer); $i++, $ofs++)
            $buffer[$ofs] = $match[0][$i];
    }
    return $buffer;
}

$str = 'commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate '
      .'velit esse<br> quam nihil molestiae consequatur,  vel illum qui dolorem eum '
      .'fugiat quo voluptas nulla  pariatur? '
      .'<a href="test">test<p></p></a><span>test<p></p>bla';

var_dump(StripUnclosedTags($str));

输出

string 'commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea
voluptate velit esse<br/> quam nihil molestiae consequatur, 
vel illum qui dolorem eum fugiat quo voluptas nulla 
pariatur? <a href="test">test<p></p></a>' (length=226)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 2016-03-30
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多