PHP 删除所有空格,除非条件


php remove all spaces UNLESS condition

标题几乎是不言自明的...

我想删除所有空格,除非它位于" "''

例如:

<?php
$myText = <<<EOF
   echo 'Those spaces should not be removed';    echo 'but the spaces between the semicolon TO the next echo should be removed';
EOF;
$string = str_replace(' ', '', $myText); //this remove everything :(
?>

我预计$string是:

echo'Those spaces should not be removed';echo'but the spaces between the semicolon TO the next echo should be removed';

谢谢!

试试这个:

// Break up $string into an array of separated $string_parts
while (preg_match('/''';[^'']+''/', $string)) {
preg_match('/''';[^'']+''/', $string, $pattern);
$string_explode = explode($pattern[0], $string);
$string_parts[] = $string_explode[0];
$string_parts[] = $pattern[0];
$string = $string_explode[1];
}

// Add last remaining part of original $string to $string_parts array
$string_parts[] = $string_explode[1];

// Collapse the spaces in every second element in $string_parts array
$count_string_parts = count($string_parts);
for ($i = 1; $i < $count_string_parts; $i = $i + 2) {
$string_parts[$i] = str_replace(' ', '', $string_parts[$i]);
}

// Put $string back together again from $string_parts array
$string = implode($string_parts);