Question

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"

Was it helpful?

Solution

Something like:

$s = 'Stack-Overflow Questions Tags Users';

if(preg_match_all('/\b(\w)/',strtoupper($s),$m)) {
    $v = implode('',$m[1]); // $v is now SOQTU
}

I'm using the regex \b(\w) to match the word-char immediately following the word boundary.

EDIT: To ensure all your Acronym char are uppercase, you can use strtoupper as shown.

OTHER TIPS

$s = 'Stack-Overflow Questions Tags Users';
echo preg_replace('/\b(\w)|./', '$1', $s);

the same as codaddict's but shorter

  • For unicode support, add the u modifier to regex: preg_replace('...../u',
$initialism = preg_replace('/\b(\w)\w*\W*/', '\1', $string);

Just to be completely different:

$input = 'Stack-Overflow Questions Tags Users';

$acronym = implode('',array_diff_assoc(str_split(ucwords($input)),str_split(strtolower($input))));

echo $acronym;

If they are separated by only space and not other things. This is how you can do it:

function acronym($longname)
{
    $letters=array();
    $words=explode(' ', $longname);
    foreach($words as $word)
    {
        $word = (substr($word, 0, 1));
        array_push($letters, $word);
    }
    $shortname = strtoupper(implode($letters));
    return $shortname;
}

Regular expression matching as codaddict says above, or str_word_count() with 1 as the second parameter, which returns an array of found words. See the examples in the manual. Then you can get the first letter of each word any way you like, including substr($word, 0, 1)

The str_word_count() function might do what you are looking for:

$words = str_word_count ('Stack-Overflow Questions Tags Users', 1);
$result = "";
for ($i = 0; $i < count($words); ++$i)
  $result .= $words[$i][0];
function initialism($str, $as_space = array('-'))
{
    $str = str_replace($as_space, ' ', trim($str));
    $ret = '';
    foreach (explode(' ', $str) as $word) {
        $ret .= strtoupper($word[0]);
    }
    return $ret;
}

$phrase = 'Stack-Overflow Questions IT Tags Users Meta Example';
echo initialism($phrase);
// SOQITTUME
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top