Search code examples
phphtmlpreg-replacestr-replacetrim

How can I remove empty space from the beginning of strings but inside some HTML tags using PHP?


Say I have this:

<p>  This is a paragraph.</p><p>&nbsp;This is another paragraph.</p>

I want it to be:

<p>This is a paragraph.</p><p>This is another paragraph.</p>

I cannot simply use trim() as there is the <p> at the beginning. But I also can't use the str_replace()/preg_replace() as I need to retain the empty space inside This is a paragraph. How should I achieve this? Thanks!


Solution

  • You can use regex bellow:

    (?<=>)(\s|&nbsp;)*|(\s|&nbsp;)*(?=<\/)
    

    https://regex101.com/r/fZ3oQ3/2

    PHP Code example:

    $re = "/(?<=>)(\\s|&nbsp;)*|(\\s|&nbsp;)*(?=<\\/)/"; 
    $str = "<p>  This is a paragraph.</p><p>&nbsp;This is another paragraph.</p>\n"; 
    $subst = ""; 
    
    $result = preg_replace($re, $subst, $str);