Assuming they always have the format “[Other Names] LastName”, so the last word is always a last name, you can split it into tokens by separator [space] using the php explode () function (http://php.net/ manual / en / function.explode.php)
// Given $name = "Jake Whiteman"; // Process // Tokenize, getting separate names $names = explode(' ', $name); // Pop last name into variable $last_name, keep remaining names in $names $last_name = array_pop($names); // Get last initial $last_initial = $last_name[0]; // Put first names back together $beginning = implode(' ', $names); $full_name = $beginning.' '.$last_initial.'.';
You can combine all this into a function:
function nameWithLastInitial($name) { $names = explode(' ', $name); $last_name = array_pop($names); $last_initial = $last_name[0]; return implode(' ', $names).' '.$last_initial.'.'; } $name = "Jake Whiteman"; echo nameWithLastInitial($name);
source share