phpreplaceremoving-whitespace

Replace a nominated substring and its optional leading and/or trailing whitespaces


I have a long string that can hold all these values at the same time:

hello<!>how are you? <!>I am fine<!> What is up? <!> Nothing!

I need to find all of these possibilities:

' <!> '
' <!>'
'<!> '
'<!>'

And replace them with "\n"

Can that be achieved with str_replace() in PHP?


Solution

  • If you only have those 4 possibilities, yes, then you can do that with str_replace.

    $str = str_replace( array( ' <!> ', ' <!>', '<!> ', '<!>' ), "\n", $str );
    

    Yeah, but what if there is two spaces ? Or a tab ? Do you add a spacial case for each ?

    You can either add special cases for each of those, or use regular expressions:

    $str = preg_replace( '/\s*<!>\s*/', "\n", $str );