Search code examples
phpregexpreg-replacesummernote

Remove redundant tags '<p><br></p>' in php?


Removing redundant tags <p><br></p> at the beginning and end of the string, and in the middle leaving only one.

Input:

<p><br></p><p><br></p><p><br></p><p>gfdsgfdsgfds</p><p><br></p><p><br></p><p><br></p><p>gfdsgfdsgfdsgfds</p><p><br></p><p><br></p><p><br></p>

Desired output:

<p>gfdsgfdsgfds</p><p><br></p><p>gfdsgfdsgfdsgfds</p>

Alternative desired output:

<p>gfdsgfdsgfds</p><p><br></p><p><br></p><p><br></p><p>gfdsgfdsgfdsgfds</p>

I've tried to use: preg_replace

$string = preg_replace('/(<p><br></p>)+/', '', $string);

But the result is null.


Solution

  • You need to escape the slash / character in your regex:

    $string = preg_replace('/(<p><br><\/p>)+/', '', $string);
    

    Also note that this will remove all instances where multiple of these patterns occor, resulting in the following:

    <p>gfdsgfdsgfds</p><p>gfdsgfdsgfdsgfds</p>
    

    To remove duplicates but leave one instance, could do the following:

    $string = preg_replace('/(<p><br><\/p>)+/', '<p><br></p>', $string);