Removing whitespace other than internal quotes in PHP?

I need to remove all spaces from the string, but the quotes should remain as they were.

Here is an example:

string to parse: hola hola "pepsi cola" yay output: holahola"pepsi cola"yay 

Any idea? I am sure that this can be done using regex, but any solution is fine.

+4
source share
2 answers

We could match strings or quotes with

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

Therefore, we just need to preg_match_all and combine the result.


An example :

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

Martti, resurrecting this question because he had a simple solution that allows you to replace at a time - no need for implode. (Found your question by doing some research for a general question on how to exclude patterns in regex .)

Here is our simple regex:

 "[^"]*"(*SKIP)(*F)|\s+ 

The left side of the rotation corresponds to the completion of "quoted strings" , then deliberately fails. The right side matches the space characters, and we know that they are the correct space characters, because they did not match the expression on the left.

This code shows how to use regex (see the results at the bottom of the online demo ):

 <?php $regex = '~"[^"]*"(*SKIP)(*F)|\s+~'; $subject = 'hola hola "pepsi cola" yay'; $replaced = preg_replace($regex,"",$subject); echo $replaced."<br />\n"; ?> 

Link

How to match (or replace) a pattern, except in situations s1, s2, s3 ...

+2
source

All Articles