Search code examples
phpregexuppercaselowercase

get all uppercase " words " from a text


I want to get all uppercase string from a text using regex and PHP, for example in this sentence " Hello FROM USA Tô ENGLAND "

I want to get those words " FROM USA ENGLAND ", which means the word must have uppercase characters (all the characters) not only one.

I try to use this regex but without any solution

preg_match_all('/\b([A-Z]+)\b/', $text, $matches);

Solution

  • I hope it's what do you need:

    $text = 'Hello FROM USA to ENGLAND';
    preg_match_all('/\b([A-Z]+)\b/u', $text, $matches);
    print(implode(' ', $matches[0]));
    

    Output:

    FROM USA ENGLAND
    

    You forgot to use implode function for the get string also you need only first result in $matches.