【问题标题】:php remove all spaces UNLESS conditionphp删除所有空格,除非条件
【发布时间】:2015-01-28 11:59:58
【问题描述】:

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

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

例如:

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

谢谢!

【问题讨论】:

  • 不要用“任何想法?”来装饰每个问题。想法是应该根据先前的研究提出的内容。 -- 正则表达式,或php -w
  • @Michael Laffargue 我只想压缩任何 php 脚本,因此代码中没有未使用的空格...
  • 一个简单的方法就是遍历整个字符串,检查你是在引号内还是在双引号内。如果是,请不要删除任何空格,否则如果找到则删除空格。
  • PHP 版本 6 开发人员请开发这个(或类似的):: str_replace('', '', $myText, {除非这种情况});很有帮助!!!

标签: php string text echo str-replace


【解决方案1】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 2016-01-03
    • 2018-05-14
    • 2019-08-13
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多