Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split text string into $first and $last name in php

Tags:

php

I'm developing a private message system that allows users to search for a user by their full name, e.g.: "George Washington".

I have two variables named $firstname and $lastname, and the search function orders results by relevancy (how many times you have messaged that person). How do I get a text field to split "George Washington" into $firstname="George" and $lastname="Washington"?

like image 832
centree Avatar asked Nov 30 '12 00:11

centree


People also ask

How can I split a string into two parts in PHP?

PHP | explode() Function explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs.

How can I add first name and last name in PHP?

Just use the update command: UPDATE users SET fullname = CONCAT(firstname, ' ', lastname); Note that if a user ever changes their first or last name the full name field will become out of date. You might be better off only concatenating them on SELECT.

How can I split sentences into words in PHP?

To split a string into words in PHP, use explode() function with space as delimiter. The explode() function returns an array containing words as elements of the array.


1 Answers

The simplest way is, by using explode:

$parts = explode(" ", $name); 

After you have the parts, pop the last one as $lastname:

$lastname = array_pop($parts); 

Finally, implode back the rest of the array as your $firstname:

$firstname = implode(" ", $parts); 

example:

$name = "aaa bbb ccc ddd";  $parts = explode(" ", $name); if(count($parts) > 1) {     $lastname = array_pop($parts);     $firstname = implode(" ", $parts); } else {     $firstname = $name;     $lastname = " "; }  echo "Lastname: $lastname\n"; echo "Firstname: $firstname\n"; 

Would result:

tomatech:~ ariefbayu$ php ~/Documents/temp/test.php  Lastname: ddd Firstname: aaa bbb ccc 
like image 93
ariefbayu Avatar answered Oct 13 '22 10:10

ariefbayu