Jump to content

Changes John Robert David Smith into J R D Smith


johnsmith153

Recommended Posts

The logic is pretty simple:

 

Break the string into three parts.

Iterate through each part.

For the first two parts trim the part of all but the first character.

Put the parts back together.

 

Did you try to write anything yourself?

 

One simple way would be....

<?php

  $s = "John Robert David";
  $a = explode(" ", $s);
  for ($i = 0; $i < count($a)-1; $i++) {
    $a[$i] = $a[$i][0];
  }
  echo implode(" ", $a);

?>
  

EDIT: Thorpe beat me to it only because I was adding some additional clean up to the code.  :D

 

I also added code to trim the input value and to remove duplicate spaces in the string:

 

function abbrName($name_str)
{
    //Convert to array after removing leading/trailing and duplicate spaces
    $name_parts = explode(' ', trim(preg_replace('/ ( )*/', ' ', $name_str))); //

    //Iterrate through each word (except the last) and replace with the first letter
    for ($i=0; $i<(count($name_parts)-1); $i++)
    {
        $name_parts[$i] = substr($name_parts[$i], 0, 1);
    }
    return implode(' ', $name_parts);
}

$name = "   John Robert    David Smith   ";

echo abbrName($name);

//Output: "J R D Smith"

Using a combination of explode(), array_pop(), foreach(), and implode() should do the trick.

 

One way (untested)

<?php
function initials($str) {
    $tmp = explode(' ',$str);
    $last = array_pop($tmp);
    $ntmp = array();
    foreach ($tmp as $word)
          $ntmp[] = substr($word,0,1);
    $ntmp[] = $last;
    return(implode(' ',$ntmp));
}
echo initials('One Two Three Four');
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.