How to Regex-replace multiple
tags with one
tag?

后端 未结 5 1237
误落风尘
误落风尘 2020-11-29 07:57

I want

to turn into

What\'s the pattern for this with regex?

Note: The

相关标签:
5条回答
  • 2020-11-29 08:03

    (<br />)+

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

    0 讨论(0)
  • 2020-11-29 08:12

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

    $html = preg_replace('#(<br *\/?>\s*(&nbsp;)*)+#', '<br>', $html);
    
    0 讨论(0)
  • This works fine. It works with all the combinations below.

    $html = '<br><br>
    Some text
    <br>
    <br>
    Some another<br/><br>';
    
    $html = preg_replace("/(<br.*?>\s*)+(\n)*+(<br.*?>)/","<br>",$html);
    

    $html will be changed to

    <br>
    Some text
    <br>
    Some another<br>
    
    0 讨论(0)
  • 2020-11-29 08:24
    $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 />.

    0 讨论(0)
  • 2020-11-29 08:29

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

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

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

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

    0 讨论(0)
提交回复
热议问题