phpregexpreg-replacecpu-wordtitle-case

Convert all uppercase words in a string to title case


I am trying to replace words in sentence i.e.

HELLO World WHAT foo

To

Hello World What foo

so far have way to detecting it:

preg_replace('/(\b[A-Z][A-Z]+\b)/sm','$1', $string);

but it does nothing as I can't put as an argument ucwords('$1').

P.S. this kind of methods are not good: ucwords(strtolower($string)); as I want to leave all that wasn't all-caps as it was.


Solution

  • It is slightly more efficient to use an anonymous function rather then call on the /e modifier.

       $formatted = preg_replace_callback(
            '/(\b[A-Z][A-Z]+\b)/',
            create_function(
                '$matches',
                'return ucwords(strtolower($matches[0]));'
            ),
            $string
        );