简体   繁体   中英

How to convert multiple <br/> tag to a single <br/> tag in php

Wanted to convert

<br/>
<br/>
<br/>
<br/>
<br/>

into

<br/>

You can do this with a regular expression:

preg_replace("/(<br\s*\/?>\s*)+/", "<br/>", $input);

This if you pass in your source HTML, this will return a string with a single <br/> replacing every run of them.

我的几乎与levik的(+1)相同,只是考虑了一些不同的br格式:

preg_replace('/(<br[^>]*>\s*){2,}/', '<br/>', $sInput);

较短的增强的可读性,无论属性如何,都能产生正确的输出:

preg_replace('{(<br[^>]*>\s*)+}', '<br/>', $input);

Thanks all.. Used Jakemcgraw's (+1) version

Just added the case insensative option..

{(<br[^>]*>\s*)+}i

Great tool to test those Regular expressions is:

http://www.spaweditor.com/scripts/regex/index.php

使用正则表达式匹配<br/>一次或多次,然后使用preg_replace(或类似的内容)替换为<br/>例如levik的回复。

without preg_replace, but works only in PHP 5.0.0+

$a = '<br /><br /><br /><br /><br />';
while(($a = str_ireplace('<br /><br />', '<br />', $a, $count)) && $count > 0)
{}
// $a becomes '<br />'

You probably want to use a Regular Expression. I haven't tested the following, but I believe it's right.

$text = preg_replace( "/(<br\s?\/?>)+/i","<br />", $text );

A fast, non regular-expression approach:

while(strstr($input, "<br/><br/>"))
{
    $input = str_replace("<br/><br/>", "<br/>", $input);
}

User may enter many variants

<br>
<br/>
< br />
<br >
<BR>
<BR>< br>

...and more.

So I think it will be better next

$str = preg_replace('/(<[^>]*?br[^>]*?>\s*){2,}/i', '<br>', $str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM