How to build Acronyms of a phrase in PHP

Viewed 9151

I'm looking for a way that I can extract the first letter of each word from an input field and place it into a variable.

Example: if the input field is "Stack-Overflow Questions Tags Users" then the output for the variable should be something like "SOQTU"

10 Answers
$s = "Stack-Overflow Questions IT Tags Users Meta Example";    
$sArr = explode(' ', ucwords(strtolower($s)));
$sAcr = "";
foreach ($sArr as $key) {
   $firstAlphabet = substr($key, 0,1);
   $sAcr = $sAcr.$firstAlphabet ;
}

using answer from @codaddict.

i also thought in a case where you have an abbreviated word as the word to be abbreviated e.g DPR and not Development Petroleum Resources, so such word will be on D as the abbreviated version which doesn't make much sense.

function AbbrWords($str,$amt){
        $pst = substr($str,0,$amt);
        $length = strlen($str);
        if($length > $amt){
            return $pst;
        }else{
            return $pst;
        }
    }
    
    function AbbrSent($str,$amt){
        if(preg_match_all('/\b(\w)/',strtoupper($str),$m)) {
            $v = implode('',$m[1]); // $v is now SOQTU
            if(strlen($v) < 2){
                if(strlen($str) < 5){
                    return $str;
                }else{
                    return AbbrWords($str,$amt);
                }
            }else{
                return AbbrWords($v,$amt);
            }
        }
    }
Related