Search code examples
phpregexpreg-match-allabbreviation

How to get only the uppercase first letters in PHP?


I want to transform phrases in abbreviations, but don't want every first letter of the words to compose the abbreviation, only the ones that are in uppercase. For example, I'd like to transform the string "United States of America" into "USA" and not "USOA", as all the codes I found works.

In my project I have to show a timetable of classes, and some of the classes names are big like "Linguagem de Programação Orientada a Objeto" (object-oriented programming language), and if I use the codes I found on the internet, it would turn the "Linguagem de Programação Orientada a Objeto" string into LDPOAO, and not LPOO, as it would make sense.

The code I found: (it turns a string into an abbreviation, I want to know how to select only the uppercase letters to put in $result)

$string = "Progress in Veterinary Science";

$expr = '/(?<=\s|^)[a-z]/i';
preg_match_all($expr, $string, $matches);

$result = implode('', $matches[0]);

$result = strtoupper($result);

echo $result;

Solution

  • Here is the code. Note the changes to the regular expression:

    $string = "Progress in Veterinary Science";
    
    $expr = '/(?<=\s|^)[A-Z]/';
    preg_match_all($expr, $string, $matches);    
    $result = implode('', $matches[0]);
    echo $result;