Abbreviation of the full name, so Last Name is only the first letter

After you read a few questions and checked a few other sites, I’m still not moving forward, I find an easy way to take the full name, for example, say “Jake Whitman” and crop it so that it appears on the web page, like "Jake W." obviously without speech marks around him, so there is no confusion.

Does anyone know how to do this? I am sure that this is probably just a matter of finding a space and then trimming the last name, I just cannot find a way to do this.

Thanks in advance!

+4
source share
5 answers
$names = explode( " ", $name ); echo $names[0]." ".$names[1][0]; 
+6
source

You can use this code. This will work for three phrases where it is assumed that the second word is the middle name, only the last name will be truncated.

 <?php $name = "Jake Awesome Whiteman"; $separate = explode(" ", $name); $last = array_pop($separate); echo implode(' ', $separate)." ".$last[0]."."; ?> 
+5
source

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); // Should print 'Jake W.' 
+2
source
 $name = "Jake Whiteman"; $names = explode(' ', $name); //$names[0] = "Jake", $names[1] = "Whiteman" echo $names[0]." ".substr($names[1], 0,1)."."; 
+1
source

this would be useful when only a username and username entered multiple names

 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <?php $userName = "Jakeds hfg gsd"; if(preg_match('/\s/',$userName)) { $separate = explode(" ", $userName); $last = array_pop($separate); $first = mb_strimwidth($separate[0], 0 , 15); echo $first." ".$last[0]."."; } else { $first = mb_strimwidth($userName, 0 , 15); echo $first; } //echo $first." ".$last[0]."."; ?> </body> </html> 
+1
source

All Articles