php删除多个空格

时间:2011-04-06 01:19:44

标签: php regex preg-replace

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

|实例|

我有以下字符串:“我的第一个姓氏”


我想要达到的目标是:“我的FirstLastName”

抱歉,但我对正则表达式非常糟糕:(所以任何帮助都表示赞赏。

2 个答案:

答案 0 :(得分:5)

你实际上并不需要正则表达式,只需将字符串拆分为空格然后再将其连接起来就更快了。

$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]);

答案 1 :(得分:3)

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

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