phppreg-matchacronym

Create an Acronym of a string in PHP


I want to create an Acronym of a string based on the string's value. For instance if the string has spaces like "Stackoverflow Community Forum", the acronym should be "SCF", but if there is no spaces in the string it should take the first 3 Letters of the word like "Stackoverflow" should be "STA". Another part should include that if the string is only 2 characters long, it should add a random Alphanumeric letter, example if the string is "IT" it should add it as "ITA"

Here is what I have so far. Although if I take the spaces out, I get SSTA at my second If.

The Idea of this is, the Acronym should be only 3 characters and should include incrementing numbers at the back example STA001 and next acronym SFC002 etc.

$s = 'Stackoverflow Community Forum';

if(preg_match_all('/\b(\w)/',strtoupper($s),$m)) {
    $v = implode('',$m[1]);
    echo $v;
}
if(!preg_match_all('/^\S.*\s.*\S$/',$s))
{
    $v = strtoupper(substr($s,0,3));
    echo $v;
}

I would appreciate any help. Thank you


Solution

  • This code first uses the same regex to match the first chars of each word, but it then checks it there is only 1 value found. If just 1 value it uses the first 3 chars of the whole string, otherwise just implodes the matched letters.

    Then it loops till the string is 3 chars long, adding a random char each time (this allows for 1 char strings)...

    // Test Values
    $s = 'Stackoverflow Community Forum';
    $s = 'Stackoverflow Community';
    $s = 'Stackoverflow';
    $s = 'IT';
    $s = 'I';
    
    $s =strtoupper($s);
    if(preg_match_all('/\b(\w)/', $s,$m)) {
        if ( count($m[1]) === 1 )   {
            $v = substr($s,0,3);
        }
        else    {
            $v = implode('',$m[1]);
        }
    }
    else    {
        $v = '';
    }
    // Pad to 3 chars long.
    while ( strlen($v) < 3 )    {
        $v .= chr( ord("A") + rand(0,25) );
    }
    echo $v;