johnsmith153 Posted October 9, 2008 Share Posted October 9, 2008 Title should explain. I would like a nice simple script that stores the first letter of each word, but the full final word. ie. One Two Three Four = O T T Four Quote Link to comment Share on other sites More sharing options...
trq Posted October 9, 2008 Share Posted October 9, 2008 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); ?> Quote Link to comment Share on other sites More sharing options...
Psycho Posted October 9, 2008 Share Posted October 9, 2008 EDIT: Thorpe beat me to it only because I was adding some additional clean up to the code. 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" Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted October 9, 2008 Share Posted October 9, 2008 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 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.