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"
?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With