php 如何用一个 <br /> 标签正则表达式替换多个 <br /> 标签?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7738439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:16:39  来源:igfitidea点击:

How to Regex-replace multiple <br /> tags with one <br /> tag?

phpregex

提问by Weblurk

I want <br /><br />to turn into <br />

我想<br /><br />变成<br />

What's the pattern for this with regex?

正则表达式的模式是什么?

Note: The <br />tags can occur more than 2 times in a row.

注意:<br />标签可以连续出现 2 次以上。

回答by FtDRbwLXw6

$html = preg_replace('#(<br */?>\s*)+#i', '<br />', $html);

This will catch any combination of <br>, <br/>, or <br />with any amount or type of whitespace between them and replace them with a single <br />.

这将捕获, 或之间的任何数量或类型的空格的任何组合<br>,并将它们替换为单个.<br/><br /><br />

回答by Williham Totland

You coulduse s/(<br \/>)+/<br \/>/, but if you are trying to use regex on HTML you are likely doing something wrong.

可以使用s/(<br \/>)+/<br \/>/,但如果您尝试在 HTML 上使用正则表达式,您可能会做错事。

Edit:A slightly more robust pattern you could use if you have mixed breaks:

编辑:如果您有混合休息,您可以使用稍微更强大的模式:

/(<br\ ?\/?>)+/

/(<br\ ?\/?>)+/

This will catch <br/>and <br>as well, which might be useful in certain cases.

这将捕获<br/><br>并且在某些情况下可能有用。

回答by AndrewMcLagan

The answer from @FtDRbwLXw6 is great although it does not account for &nbsp;spaces. We can extend this regex to include that as well:

@FtDRbwLXw6 的答案很好,尽管它没有考虑&nbsp;空格。我们可以扩展这个正则表达式以包含它:

$html = preg_replace('#(<br *\/?>\s*(&nbsp;)*)+#', '<br>', $html);

回答by m.edmondson

(<br />)+

(<br />)+

Will match them so you could use preg_replaceto replace them (remember to correctly escape characters).

将匹配它们,以便您可以preg_replace用来替换它们(记住正确转义字符)。