【发布时间】:2011-04-06 01:19:43
【问题描述】:
我遇到了一些麻烦,我想知道是否有人知道 preg_replace 正则表达式可以删除字符串中除第一个空格之外的所有空格。
|示例|
我有以下字符串:“我的名字”
我想要实现的是:“My FirstLastName”
对不起,我对正则表达式很不满意 :( 所以任何帮助表示赞赏。
【问题讨论】:
标签: php regex preg-replace
我遇到了一些麻烦,我想知道是否有人知道 preg_replace 正则表达式可以删除字符串中除第一个空格之外的所有空格。
|示例|
我有以下字符串:“我的名字”
我想要实现的是:“My FirstLastName”
对不起,我对正则表达式很不满意 :( 所以任何帮助表示赞赏。
【问题讨论】:
标签: php regex preg-replace
您实际上并不需要正则表达式来执行此操作,只需将字符串拆分为空格然后再将其连接起来会更快。
$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]);
【讨论】:
无需使用正则表达式,只需找到第一个空格,保留那段字符串,然后替换其余部分:
$first_space = strpos($string, ' ');
$string = substr($string, 0, $first_space+1)
. str_replace(' ', '', substr($string, $first_space+1));
【讨论】: