I have short strings like this
$str = 'abc | xx ?? "1 x \' 3" d e f \' y " 5 \' x yz';
I want to remove all spaces from a string that are not enclosed in single or double quotes. Any characters enclosed in single or double quotes should not be changed. As a result, I expect:
$expected = 'abc|xx??"1 x \' 3"def\' y " 5 \'xyz';
My current solution based on character-wise comparisons is the following:
function removeSpaces($string){
$ret = $stop = "";
for($i=0; $i < strlen($string);$i++){
$char = $string[$i];
if($stop == "") {
if($char == " ") continue;
if($char == "'" OR $char == '"') $stop = $char;
}
else {
if($char == $stop) $stop = "";
}
$ret .= $char;
}
return $ret;
}
Is there a solution that is smarter?