Search code examples
phpuppercasespaces

How to make ctype_upper ignore spaces on uppercase check?


I have the following in part of my code. It checks to see if $item is uppercase and if so adds a class of 'uppercase' to the div element.

`echo "<div class='". $alt . "'><div class='menu-item";

        if (ctype_upper($item)) { 
            echo " uppercase";
        } 
        echo "'>" .$item . "</div>";`

However if the string $item contains any spaces (such as 'THIS STRING') this class attribute of 'uppercase' does not get applied.

Does anyone have a ideas on how to avoid this from happening.

Thanks in advance


Solution

  • You can temporarily remove the spaces from $item before testing:

    if (ctype_upper(str_replace(' ', '', $item))
    

    However it's probably a good idea to do this inside your own function as a level of abstraction:

    function isMenuItemUpperCase($item) {
        return ctype_upper(str_replace(' ', '', $item);
    }
    

    And then:

    if (isMenuItemUpperCase($item))
    

    This way the call site (last line) is very clear to read and you have a central location from which the behavior can change in the future if the need arises.