Link to home
Start Free TrialLog in
Avatar of rfila
rfila

asked on

Getting someones initials from a string of their name in PHP

Hi

I have a string of a name eg "Benjamin James Smith".

I need to get the initials of that name into another string eg "BJS".

At present I am having to split the string by spaces and substr each element of the array.  I'm sure their must be a simple way with ereg_replace but I dont have a good enough understanding of the characters you put into that function to make it do what you want!

Can someone tell me how to perform the above function and also point me in the right direction for documentation of how that function works.

Thanks
Rich
Avatar of Roonaan
Roonaan
Flag of Netherlands image

Try the next line:

echo ereg_replace('[^A-Z]','', ucwords(strtolower($name)));

There will be an preg variant offcourse, but this is the ereg version.

Regards

-r-
Avatar of nesnemis
nesnemis

Hi rfila,
try this:

$nameArray = split(" ", $usersFullName);
$initials = "";
for($i=0; $i<$nameArray.length(); $i++)
    $initials .= nameArray[$i][0];
echo $initials;

nesnemis
Re: nesnemis:

>At present I am having to split the string by spaces and substr each element of the array.

Therefor your solution isn't quite a solution in this case.

Furthermore $nameArray.length() is nonexisting in php - to my knowledge at least.

Evenso, if you would use the php equivalent of length() (eq: count($nameArray)) you're code would still be inefficient and should be something like:

<?php
$nameArray = split(" ", $usersFullName);
foreach($nameArray as $name)
  echo substr(trim($name),0,1);
?>

Regards

-r-
<?
$name="Experts Exchange";
$nameArray=explode(" ",$name);
$initials="";
for ($i=0;$i<sizeof($nameArray);$i++) {
$nameTemp=substring($nameArray[$i],0,1);
$initials.=$nameTemp;
}

$initials=strtoupper($initials);

echo "Initials: $initials";
?>
forgot something.  change:

$nameTemp=substring($nameArray[$i],0,1);

to:

$nameTemp=substr(trim($nameArray[$i]),0,1);
try this regular expression,

preg_match_all("/\b\S/","Benjamin James Smith",$out);
foreach($out as $value){
        echo implode("",$value);
}
pfff. the better use $text = ereg_replace("[A-Z]",'',$text);

But that solution will not prevent issues with usernames which aren't entered with capitals.

Therefor you should use ucwords(strtolower($text)) to get all and only the first letters of each word in uppercase.

Also mattjp88's is nice, but is what rfila already has, and asked us to improve...

-r-
ASKER CERTIFIED SOLUTION
Avatar of eeBlueShadow
eeBlueShadow

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial