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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)