How would I remove all spaces between single quotes skipping escaped quotes in PHP
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"
<?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
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
Try this:
<?php
$str = " testing ' this is a \'test\' ' zzz ";
echo trim($str," ");
?>
精彩评论