0

I have a PHP function that is supposed to make the first letter of each word uppercase and all other letters lowercase. By default, in my function an exception is made if all letters of a word are uppercase, in which case that word should be left all uppercase. UNLESS I pass in true for the 2nd param ($disallowAllUppercase) -- in which case all caps won't be allowed (the first letter of each word forced caps, all other letters forced lowercase).

I got most of the following function from a stack overflow post but cannot remember where. It mostly works correctly, but I found a case where it falls down:

function NormalizeWords($str, $disallowAllUppercase = false){
    $parts = explode(' ', $str);

    if($disallowAllUppercase){
        $result = array_map(function($x){
            return ucwords(strtolower($x));
        }, $parts);
    }else{
        $result = array_map(function($x){
            if (!ctype_upper($x)) {
                return ucwords(strtolower($x));
            }
            return $x;
        }, $parts);
    }

    return implode(' ', $result);
}
function writeme($str){
    echo $str . "<br>";
}

When I run the following:

writeme(NormalizeWords("ABC1"));
writeme(NormalizeWords("ABC1", true));
writeme(NormalizeWords("ABC1", false));

...I get the following results:

Abc1
Abc1
Abc1

Expected results:

ABC1
Abc1
ABC1

In summary, if there is only 1 word and that word contains a number, it doesn't work.

What changes do I need to make to this function to get it to work correctly in all cases?

HerrimanCoder
  • 6,835
  • 24
  • 78
  • 158

0 Answers0