开发者

preg_replace - replace a tag that appears 3 or more times

开发者 https://www.devze.com 2023-03-31 02:01 出处:网络
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 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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号