preg_replace - replace a tag that appears 3 or more times
I'm trying to use preg_replace to replace <br />
when it appears 3 or more times, it should be replaced with <br /><br /&g开发者_开发百科t;
I'm trying to use this: $text=preg_replace('/(<br \/>){3,}/', '<br /><br />', $text);
Any body know whats wrong with my code?
So, just to confirm... <br /><br /><br /><br /><br /><br /><br /><br />
should be replaced with <br /><br />
Your regex works just fine, the problem is if you encounter:
<br>
<br -multiple spaces- >
<br/>
<br -multiple spaces- />
<br /> <br />
note the space(s) between the 2 br's<br> -newlines- <br>
So here's a solution:
$text = '<br /><br><br /><br ><br /><br><br/><br /><br><br>
<br/>
<br/>
';
$text=preg_replace('/(<br\s*\/?>\s*){3,}/', '<br /><br />', $text);
var_dump($text); // output: string '<br /><br />' (length=12)
Online demo
精彩评论