Jeff
Jeff

Reputation: 4003

PHP retrieve last name from full name, where last name is unknown

Basic question for PHP experts out there.

I'm writing a page where the variable I receive will be somebody's full name, the two words will be separated by a space. Thus, I know that the second word, after the space will be the last name. I would like to retrieve this last name and hold it in a variable.

For example: $EditorName = "John Doe"

I would like to have the result $LastName = "Doe"

Can I use some variation of the split in the PHP manual.

I would be grateful for your help.

Upvotes: 0

Views: 126

Answers (3)

RiaD
RiaD

Reputation: 47620

$names=explode(' ',$EditorName);
$LastName=$names[1]

PHP Manual: explode

If you need really last(not second) name you should use

$LastName=array_pop($names) instead

Upvotes: 2

Jacob
Jacob

Reputation: 43229

$EditorName = "John Doe";
$tmp = explode(" ", $EditorName);
$LastName = $tmp[1];
echo $LastName;

http://codepad.org/JEZXZHJR

But, what about people with middle names? More than one space in their surname? I hope former german minister Karl Theodor Maria Nikolaus Johann Jacob Philipp Franz Joseph Sylvester Freiherr von und zu Guttenberg doesn't use your script!

Upvotes: 1

svlada
svlada

Reputation: 3288

You can use regex(Regular Expressions) to extract Last name from Full name.

\s([a-zA-Z]*)

Extract results from matched group 1.

Upvotes: 0

Related Questions