Search code examples
phpstr-replaceparagraphs

Multiple <br /><br><br/>\r\n occurences needs to be replaced with <br />


I need to replace multiple occurences of <br />, <br>, <br/>, \r, \n, \r\n with only 1 <br />, but only where it shows up together so that I can split paragraphs into an array and trim out the last line break of br tag at the end of the string...

An Example of a string could be as follows:

This is paragraph 1<br>

This is paragraph 2<br /><br>



This is paragraph 3
This is paragraph 4


This is paragraph 5<br/>
This is paragraph 6


This is paragraph 7<br />This is paragraph 8

This is paragraph 9<br>

What I've tried:

$description = !empty($results['Description']) ? strip_tags(rtrim(str_replace(array("\n", "\r", "\r\n", "<br>", "<br/>", "<br />"), array("<br />"), $results['Description']), '<br />'), '<br><a>') : '';

$paragraphs = array_filter(explode("<br />", $description));

But this trims out all line breaks. I need to maintain line breaks where they are in the string, but only want to do 1 linebreak and remove all others. How to do this?

Note: I am using strip_tags because I want to only allow <br> and <a> tags in the $description string.


Solution

  • You may want to try first exploding with end of line (PHP_EOL), strip out everything but the <a>, then array_filter(), implode(), and trim():

    $str    =   'This is paragraph 1<br>
    
    This is paragraph 2<br /><br>
    
    
    
    This is paragraph 3
    This is paragraph 4
    
    
    This is paragraph 5<br/>
    This is paragraph 6
    
    
    This is paragraph 7<br />';
    
    $str    =   trim(implode('<br />'.PHP_EOL,array_filter(explode(PHP_EOL,strip_tags($str,'<a>')))));
    
    echo $str;
    

    Gives you:

    This is paragraph 1<br />
    This is paragraph 2<br />
    This is paragraph 3<br />
    This is paragraph 4<br />
    This is paragraph 5<br />
    This is paragraph 6<br />
    This is paragraph 7
    

    Your second scenario:

    $str    =   'This is paragraph 1<br>
    
    This is paragraph 2<br /><br>
    
    
    
    This is paragraph 3
    This is paragraph 4
    
    
    This is paragraph 5<br/>This is paragraph 5
    This is paragraph 6
    
    
    This is paragraph 7<br />';
    
    # Explode on line breaks and remove empty lines
    $exp    =   array_filter(explode(PHP_EOL,$str));
    # Loop array and filter the lines
    $new    =   array_map(function($v) {
                    return strip_tags(trim($v,'<br>,<br />,<br/>'),'<a><br>');
                },$exp);
    # Implode the array back
    echo implode('<br />'.PHP_EOL,$new);
    

    Gives you:

    This is paragraph 1<br />
    This is paragraph 2<br />
    This is paragraph 3<br />
    This is paragraph 4<br />
    This is paragraph 5<br/>This is paragraph 5<br />
    This is paragraph 6<br />
    This is paragraph 7