Search code examples
phpregexparsingwhitespacequotation-marks

Removing whitespace-characters, except inside quotation marks in PHP?


I need to remove all whitespace from string, but quotations should stay as they were.

Here's an example:

string to parse:
hola hola "pepsi cola" yay

output:
holahola"pepsi cola"yay

Any idea? I'm sure this can be done with regex, but any solution is okay.


Solution

  • We could match strings or quotations with

    [^\s"]+|"[^"]*"
    

    So we just need to preg_match_all and concatenate the result.


    Example:

    $str = 'hola hola "pepsi cola" yay';
    
    preg_match_all('/[^\s"]+|"[^"]*"/', $str, $matches);
    
    echo implode('', $matches[0]);
    // holahola"pepsi cola"yay