tags:

views:

56

answers:

3

Exactly as the title asks:

How would I remove all unnecessary spaces between single quotes skipping escaped quotes in PHP?

I am looking for a fast implementation to pre-prep for parsing. I would prefer not to use regex if it would be slower than using a simple loop.

(The double quotes below are for display purposes only)

examples would be:

input:

"    testing    '  this  is a     \'test\'  '     zzz     "

output:

"testing '  this  is a     \'test\'  ' zzz"
A: 
<?php
$str = "    testing    '  this  is a     \'test\'  '     zzz     ";

echo trim($str," ");

?>

try this

Treby
That will remove spaces inside single quotes. Not what I am looking for.
Mike Curry
A: 

Alright, psuedocode time:

var shouldtrim = true;
var escaped = false;
foreach char in string
    if char is whitespace and lastchar is whitespace and shouldtrim
        remove char from string

    if char is ' and not escaped
        toggle shouldtrim

    if char is \
        toggle escaped
    else
        escaped = false
Anon.
+1  A: 
<?php

$parts = preg_split('/((?<!\\\\)|(?<=\\\\\\\\))\'/', trim($data));

foreach ($parts as $index => &$part) {
    if ($index % 2 == 0) {
        $part = preg_replace('/\s{2,}/', ' ', $part);
    }
}

echo join('\'', $parts);

Now to wait for the much simpler solution I've missed :p

enbuyukfener
How does this handle a string containing `\\'`? Given that the apostrophe isn't escaped.
Anon.
Thanks Anon, edited answer to support escaped backslashes.
enbuyukfener