PHP正则表达式来清理重复的HTML标记

时间:2009-09-01 19:20:07

标签: php regex

我正在尝试使用正则表达式,但没有太多运气。

我正在阅读的源文件(格式不佳,但我无法在那里做)在元素之间的源代码中有以下内容

<BR>
<BR>
<BR>

如何将其与php正则表达式匹配?

3 个答案:

答案 0 :(得分:5)

这样的事情:

preg_match('/(<br>\s*){3}/i', $str, $matches);

这比你的例子宽松一点 - 它做了一个不区分大小写的匹配并匹配<br>之间的任何空格,而不仅仅是换行符。

匹配3个或更多而不是3:

preg_match('/(<br>\s*){3,}/i', $str, $matches);

答案 1 :(得分:3)

如果您只想替换<BR>个实例,那么最好更换字符串。它比正则表达快得多。

$newstr = str_replace('<BR>', 'replacement...', $str);

答案 2 :(得分:1)

我对它的看法

<?php

$html = <<<HTML
<BR>
<BR>
<BR>
<p>^^ Replace 3 consecutive BR tags with nothing</p>
<BR>
<BR>
<p>^^ those should stay, there's only 2 of them</p>
<BR>
  <BR>


      <BR>
<p>^^ But those should go, whitespace and newlines shouldn't matter
HTML;

echo preg_replace( "/(?:<br>\s*){3}/i", '', $html );