Home » Php » How to check if letter is upper or lower in PHP?

How to check if letter is upper or lower in PHP?

Posted by: admin November 29, 2017 Leave a comment

Questions:

I have texts in UTF-8 with diacritic characters also, and would like to check if first letter of this text is upper case or lower case. How to do this?

Answers:
function starts_with_upper($str) {
    $chr = mb_substr ($str, 0, 1, "UTF-8");
    return mb_strtolower($chr, "UTF-8") != $chr;
}

Note that mb_substr is necessary to correctly isolate the first character.

Questions:
Answers:

Use ctype_upper for check upper case:

$a = array("Word", "word", "wOrd");

foreach($a as $w)
{
    if(ctype_upper($w{0}))
    {
        print $w;
    }
}

Questions:
Answers:

Tried ?

$str = 'the text to test';
if($str{0} === strtoupper($str{0})) {
   echo 'yepp, its uppercase';
}
else{
   echo 'nope, its not upper case';
}

Questions:
Answers:

As used in Kohana 2 autoloader function:

echo $char < 'a' ? 'uppercase' : 'lowercase';

When a string character is cast to integer it evaluates to its ASCII number. As you know in the ASCII table first there are some control characters and others. Then the uppercase letters from the Latin alphabet. And then the lowercase letters from the Latin alphabet. Thus you can easily check whether the code of a letter is smaller or bigger than the small latin character a.

BTW this is around twice as fast than a solution with regular expressions.

Questions:
Answers:

I didn’t want numbers and others to be an upper char, so I use:

if(preg_match('/[A-Z]$/',$char)==true)
{
   // this must be an upper char
   echo $char
}

Questions:
Answers:

Note that PHP provides the ctype family like ctype_upper.

You have to set the locale correctly via setLocale() first to get it to work with UTF-8.
See the comment on ctype_alpha for instance.

Usage:

if ( ctype_upper( $str[0] )) {
    // deal with 1st char of $str is uppercase
}

Questions:
Answers:

What about just:

if (ucfirst($string) == $string) {dosomething();}

Questions:
Answers:
if(ctype_upper(&value)){
    echo 'uppercase';
}
else {
    echo 'not upper case';
}

Questions:
Answers:

If you want it in a nice function, I’ve used this:

function _is_upper ($in_string)
{
    return($in_string === strtoupper($in_string) ? true : false);
}

Then just call..

if (_is_upper($mystring))
{
  // Do....
}

Leave a Reply

Your email address will not be published. Required fields are marked *