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 Link to comment https://forums.phpfreaks.com/topic/127697-changes-john-robert-david-smith-into-j-r-d-smith/ 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); ?> Link to comment https://forums.phpfreaks.com/topic/127697-changes-john-robert-david-smith-into-j-r-d-smith/#findComment-660865 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" Link to comment https://forums.phpfreaks.com/topic/127697-changes-john-robert-david-smith-into-j-r-d-smith/#findComment-660868 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 Link to comment https://forums.phpfreaks.com/topic/127697-changes-john-robert-david-smith-into-j-r-d-smith/#findComment-660869 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.