【问题标题】:PHP How to trim whitespaces a from stringPHP如何从字符串中修剪空格
【发布时间】:2014-06-03 19:38:55
【问题描述】:

我想知道如何替换字符串中的空格。

示例字符串: INFO [06:57:18 INFO]: 03.06 07:05:32 Auto-saving 03.06 07:05:32 [Console] INFO CONSOLE: Enabled level saving 03.06 07:05:32 [Console] INFO CONSOLE

我想成功: INFO [06:57:18 INFO]: 03.06 07:05:32 Auto-saving 03.06 07:05:32 [Console] INFO CONSOLE: Enabled level saving 03.06 07:05:32 [Console] INFO CONSOLE

我尝试了以下对我不起作用的方法:

preg_replace('/\s+/', '', $foo);
trim($foo);

我尝试将其打印为 json 以查看实际情况并得到以下输出: http://pastebin.com/QY8uGt4V(输出很大)

【问题讨论】:

  • 你是它的空白吗?应该是换行符,制表符
  • preg_replace('/\b+/', '', $foo);
  • @JohnConde 我认为这会更容易:$foo = preg_replace('/\b+/', '', $foo);
  • 收到此错误:Warning: preg_replace(): Compilation failed: nothing to repeat at offset 2 in

标签: php whitespace removing-whitespace


【解决方案1】:

试试这个:

preg_replace('/[\b]+/', '', $str);

【讨论】:

    【解决方案2】:

    试试这个

    $str = 'INFO                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          [06:57:18 INFO]: 03.06 07:05:32 Auto-saving 03.06 07:05:32 [Console] INFO CONSOLE: Enabled level saving 03.06 07:05:32 [Console] INFO CONSOLE;';
    $output = preg_replace('!\s+!', ' ', $str);
    echo $output;
    

    【讨论】:

    • 没有没有用。我还尝试了preg_replace('!\s+!', '', $str);,它删除了所有空格。
    【解决方案3】:

    您想要做的是用一个替换多个空格?如果所以你只需要设置一个空格字符作为替换,像这样:

    preg_replace('/\s+/', ' ', $foo);
    trim($foo);
    

    【讨论】:

      猜你喜欢
      • 2010-09-16
      • 2010-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 2016-01-21
      相关资源
      最近更新 更多