Search code examples
phpstringcpu-wordtext-parsingacronym

Create acronym from a string containing only words


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"


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.