0

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"
2
  • Your example doesn't seem very clear. It looks like you want to strip excess spaces that are ... between double-quotes but not single-quotes?
    – Anon.
    Jan 12, 2010 at 3:45
  • You're correct, I will edit my posting. Ty.
    – Kladskull
    Jan 12, 2010 at 3:48

3 Answers 3

1
<?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

1
  • 1
    How does this handle a string containing \\'? Given that the apostrophe isn't escaped.
    – Anon.
    Jan 12, 2010 at 3:57
0

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
-1

Try this:

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

echo trim($str," ");

?>
1
  • 1
    That will remove spaces inside single quotes. Not what I am looking for.
    – Kladskull
    Jan 12, 2010 at 3:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.