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

时间:2014-11-30 10:14:33

标签: php string text echo str-replace

标题非常自我解释......

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

例如:

<?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';

谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个:

// 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);