如何删除多余的< br/>使用PHP从HTML代码中获取标签? [英] How to remove redundant <br /> tags from HTML code using PHP?
问题描述
我正在用PHP解析一些凌乱的HTML代码,其中有一些多余的
标记,我想对其进行一些清理.例如:
I'm parsing some messy HTML code with PHP in which there are some redundant
tags and I would like to clean them up a bit. For instance:
<br>
<br /><br />
<br>
我该如何使用preg_replace()替换类似的内容?:
How would I replace something like that with this using preg_replace()?:
<br /><br />
换行符,空格以及< br>
,< br/>
和< br/>
必须全部考虑.
Newlines, spaces, and the differences between <br>
, <br/>
, and <br />
would all have to be accounted for.
基本上,我想将三个或三个以上连续休息的每个实例替换为两个.
推荐答案
这里是您可以使用的东西.只要有2个或更多< br>
标记(空格之间以及不同类型之间),第一行就会找到,并用格式正确的< br/>< br/>替换它们.
.
Here is something you can use. The first line finds whenever there is 2 or more <br>
tags (with whitespace between and different types) and replace them with wellformated <br /><br />
.
如果您也想要的话,我还添加了第二行来清理< br>
标记的其余部分.
I also included the second line to clean up the rest of the <br>
tags if you want that too.
function clean($txt)
{
$txt=preg_replace("{(<br[\\s]*(>|\/>)\s*){2,}}i", "<br /><br />", $txt);
$txt=preg_replace("{(<br[\\s]*(>|\/>)\s*)}i", "<br />", $txt);
return $txt;
}
这篇关于如何删除多余的< br/>使用PHP从HTML代码中获取标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!