How to get a last name

Possible duplicate:
Regex - Return First and Last Name

Hello,

I have the full name of users stored in one field. How can I get the full first and last name first. This is what I'm using right now:

$first = substr($full_n, 0, strpos($full_n,' ')); 
+4
source share
5 answers

(not an answer, but too big to be a comment)

There is no solution to this problem, you just need to decide how you will cripple the names of people.

There are already several worthy examples in the answers, but in their comments they will all lose on Pekka's examples. Some names, such as Hillary Rodham Clinton , are often decrypted by Hillary Rodham-Clinton and will be less problematic.

Simple, common examples, such as John von Neumann or Phillip de la Cruz , will still fail.

+1
source
 list ($first, $last) = explode(' ', $full_n, 2); echo "$first {$last[0]}."; 

Will not work with more than two names, like all other solutions. You must save everything (first name, middle name, last name, ...) separately if you want to do more with it than just display.

Update:

Inspired by Pekka (comments on the question;))

 $names = explode(' ', $full_n); $first = array_shift($names); $last = array_pop($names); echo "$first {$last[0]}."; 

This works for an arbitrary (> = 2) number of names, but displays only the first (full) and last (abbreviated). Something like Schmidt-Muller will look curious ("S").

+5
source

Well, you're almost there ...

If this ensures that your users will have two names (only the first and last, without spaces), you can simply do this:

 $full_n = 'Demian Brecht'; $first = substr($full_n, 0, strpos($full_n,' ')+2); print_r($first); 

However, if you are dealing with names> 2, you will have to rethink your logic.

+2
source
 $full_n = trim($full_n); // remove extra spaces $first_name = substr($full_n, 0, strpos($full_n, ' ')); $last_initial = substr($full_n, strrchr($full_n, ' '), 1); $result = trim($first_name . ' ' . $last_initial); 
+1
source

It was difficult for me to understand this question. If you want to get the full name and first initial of the last name.

 $firstwithlastnameinitial = substr($full_n, 0, strpos($full_n, ' ')) . substr($full_n, strpos($full_n, ' ') + 1, 1); 

OR

 list ($fname, $lname) = explode(' ', $full_n, 2); $lastwithfirstinitial = $fname . substr($lname, 0, 1); 

If you want to get the full last name with the first initial of the first name:

 $lastwithfirstinitial = substr($full_n, strpos($full_n, ' ') + 1, strlen($full_n)) . substr($full_n, 0, 1); 

This should get the last name plus the first initial. Or something easier to read.

 list ($fname, $lname) = explode(' ', $full_n, 2); $lastwithfirstinitial = $lname . substr($fname, 0, 1); 
+1
source

All Articles