Thursday, 11 August 2016

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


$string = "This is test by viral";
//$string = "This";
//$string = "This is ";

$string = trim($string);

The simplest way is, by using explode:
$parts = explode(" ", $string);



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);


echo '<hr/>';
echo '<strong>First name</strong> :'.$firstname;
echo '<hr/>';
echo '<strong>Last name</strong> :'.$lastname;
echo '<hr/>';

No comments:

Post a Comment