开发者

php remove more than one space

开发者 https://www.devze.com 2023-02-22 14:25 出处:网络
I\'ve been having some trouble, i was wondering if anyone knows of a preg_replace regex which can remove all spaces except the first one it enc开发者_如何学Counters from a string.

I've been having some trouble, i was wondering if anyone knows of a preg_replace regex which can remove all spaces except the first one it enc开发者_如何学Counters from a string.

|EXAMPLE|

I have the following string: "My First Last Name"


What i would like to achieve is something like: "My FirstLastName"

Sorry but i'm pretty bad with regex :( so any help is appreciated.


You don't actually need regex to do that, it's quicker to just split the string on spaces and then join it up again.

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


No need to use regex, just find the first space, keep that piece of the string, and replace the rest:

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

精彩评论

暂无评论...
验证码 换一张
取 消