【问题标题】:php remove more than one spacephp删除多个空格
【发布时间】:2011-04-06 01:19:43
【问题描述】:

我遇到了一些麻烦,我想知道是否有人知道 preg_replace 正则表达式可以删除字符串中除第一个空格之外的所有空格。

|示例|

我有以下字符串:“我的名字”


我想要实现的是:“My FirstLastName”

对不起,我对正则表达式很不满意 :( 所以任何帮助表示赞赏。

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

    您实际上并不需要正则表达式来执行此操作,只需将字符串拆分为空格然后再将其连接起来会更快。

    $name = "My First Last Name"
    $pieces = explode(" ", $name, 2); // split into 2 strings
    // $pieces[0] is before the first space, and $pieces[1] is after it
    // so we can make the new string joining them together 
    // and just removing all spaces from $pieces[1]
    $newName = $pieces[0] . " " . str_replace(" ", "", $pieces[1]);
    

    【讨论】:

      【解决方案2】:

      无需使用正则表达式,只需找到第一个空格,保留那段字符串,然后替换其余部分:

      $first_space = strpos($string, ' ');
      $string = substr($string, 0, $first_space+1) 
         . str_replace(' ', '', substr($string, $first_space+1));
      

      【讨论】:

      • 你发布的代码没有做我需要的,它从字符串中删除了所有空格。
      猜你喜欢
      • 1970-01-01
      • 2011-01-20
      • 2012-01-24
      • 1970-01-01
      • 2014-02-18
      • 1970-01-01
      • 2012-01-30
      • 2016-05-08
      相关资源
      最近更新 更多