Domanda

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

È stato utile?

Soluzione

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.

Altri suggerimenti

I think its better to remove all possible white space and special charters before you use ctype_upper

Example

$alt = "Test Alt";
$item = "THIS STRING \t:\t HI";

printf("<div class='%s'><div class='menu-item %s' > %s </div> </div>", $alt, isUpper($item), $item);

HTML Output

<div class="Test Alt">
   <div class="menu-item uppercase"> THIS STRING    :    HI </div>
</div>

Function Used

function isUpper($item) {
    return ctype_upper(preg_replace('/\W+/', '', $item)) ? "uppercase" : "";
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top