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 ...
source share