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

?>
  

Link to comment
Share on other sites

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"

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.