user8715344
user8715344

Reputation:

Separate string in php by upper case letters

I'm developing an application that takes a full name of a person and then processes it. For example, if the user enters the name like this:

"AlanMichel"

Then the result must be:

"Alan Michel"

I didn't know how I can do that in the php. Anyone can help please?

Upvotes: 0

Views: 43

Answers (2)

Eddie
Eddie

Reputation: 26844

You can do:

$str = "AlanMichel";
$name = preg_split('/(?=[A-Z])/',$str);

echo implode( " ", $name );

This will result to:

Alan Michel 

Upvotes: 2

shubham715
shubham715

Reputation: 3302

Try this

function splitAtUpperCase($s) {
        return preg_split('/(?=[A-Z])/', $s, -1, PREG_SPLIT_NO_EMPTY);
}

$str = "AlanMichel";
$strArray = splitAtUpperCase($str));
echo $strArray[0]; //first name
echo $strArray[1]; //second name

Output

Alan
Michel

If you don't need the array itself, you can just preprend uppercase characters (except the first) with a space

echo  preg_replace('/(?<!^)([A-Z])/', ' \\1', $str); 

Upvotes: 0

Related Questions