How to Check If Letter Is Upper or Lower in PHP

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

It is my opinion that making a preg_ call is the most direct, concise, and reliable call versus the other posted solutions here.

echo preg_match('~^\p{Lu}~u', $string) ? 'upper' : 'lower';

My pattern breakdown:

~      # starting pattern delimiter 
^ #match from the start of the input string
\p{Lu} #match exactly one uppercase letter (unicode safe)
~ #ending pattern delimiter
u #enable unicode matching

Please take notice when ctype_ and < 'a' fail with this battery of tests.

Code: (Demo)

$tests = ['âa', 'Bbbbb', 'Éé', 'iou', 'Δδ'];

foreach ($tests as $test) {
echo "\n{$test}:";
echo "\n\tPREG: " , preg_match('~^\p{Lu}~u', $test) ? 'upper' : 'lower';
echo "\n\tCTYPE: " , ctype_upper(mb_substr($test, 0, 1)) ? 'upper' : 'lower';
echo "\n\t< a: " , mb_substr($test, 0, 1) < 'a' ? 'upper' : 'lower';

$chr = mb_substr ($test, 0, 1, "UTF-8");
echo "\n\tMB: " , mb_strtoupper($chr, "UTF-8") == $chr ? 'upper' : 'lower';
}

Output:

âa:
PREG: lower
CTYPE: lower
< a: lower
MB: lower
Bbbbb:
PREG: upper
CTYPE: upper
< a: upper
MB: upper
Éé: <-- trouble
PREG: upper
CTYPE: lower <-- uh oh
< a: lower <-- uh oh
MB: upper
iou:
PREG: lower
CTYPE: lower
< a: lower
MB: lower
Δδ: <-- extended beyond question scope
PREG: upper <-- still holding up
CTYPE: lower
< a: lower
MB: upper <-- still holding up

If anyone needs to differentiate between uppercase letters, lowercase letters, and non-letters see this post.


It may be extending the scope of this question too far, but if your input characters are especially squirrelly (they might not exist in a category that Lu can handle), you may want to check if the first character has case variants:

\p{L&} or \p{Cased_Letter}: a letter that exists in lowercase and uppercase variants (combination of Ll, Lu and Lt).

  • Source: https://www.regular-expressions.info/unicode.html

To include Roman Numerals ("Number Letters") with SMALL variants, you can add that extra range to the pattern if necessary.

https://www.fileformat.info/info/unicode/category/Nl/list.htm

Code: (Demo)

echo preg_match('~^[\p{Lu}\x{2160}-\x{216F}]~u', $test) ? 'upper' : 'not upper';

How to check if input value begins with an uppercase/ or if it has lowercases/ or if it's all uppercase in PHP?

  1. To check the first letter with upper case try below

    preg_match("/^[A-Z]/", 'Bamboozler');// This will return true if first letter is upper case
  2. To check all the character of a string lowercase, you can use ctype_lower() function

    ctype_lower('bamboozler');// This will return true if all the character are lower cases.
  3. To check all the character of a string uppercase, you can use ctype_upper() function

    ctype_upper('BOOM');// This will return true if all the character is upper cases.

How to detect if string contains 1 uppercase letter in PHP

Some regular expression should be able to the work, you can use preg_match and [A-Z]

if(preg_match('/[A-Z]/', $domain)){
// There is at least one upper
}

What is best way to test uppercase or lowercase type of a given character in php?

I feel the most direct way would be to write a regex pattern to determine the character type.

In the following snippet, I'll search for uppercase letters (including unicode) in the first capture group, or lowercase letters in the second capture group. If the pattern makes no match, the character is not a letter.

A good reference for unicode letters in regex: https://regular-expressions.mobi/unicode.html

Writing two capture groups separated by a pipe means each type of letter will be slotted into a different indexed element in the output array. [0] is the fullstring match (never used in this case, but its generation is unavoidable). [1] will hold the uppercase match (or be empty when there is a lowercase match -- as a placeholding element). [2] will hold the lowercase match -- it will only be generated if there is a lowercase match.

For this reason, we can assume the highest key in the matches array will determine the casing of the letter.

If the input character is a non-letter, preg_match() will return the falsey result of 0 to represent the number of matches, when this happens 0 is used with the lookup to access neither.

Code: (Demo) (Pattern Demo)

$lookup = ['neither', 'upper', 'lower'];
$tests = ['A', 'z', '+', '0', 'ǻ', 'Ͱ', null];

foreach ($tests as $test) {
$index = preg_match('~(\p{Lu})|(\p{Ll})~u', $test, $out) ? array_key_last($out) : 0;
echo "{$test}: {$lookup[$index]}\n";
}

Output:

A: upper
z: lower
+: neither
0: neither
ǻ: lower
Ͱ: upper
: neither

For anyone who is not yet on php7.3, you can call end() then key() like this:

Code: (Demo)

foreach ($tests as $test) {
if (preg_match('~(\p{Lu})|(\p{Ll})~u', $test, $out)) {
end($out); // advance pointer to final element
$index = key($out);
} else {
$index = 0;
}
echo "{$test}: {$lookup[$index]}\n";
}

My first approach makes a minimum of one function call per test, and a maximum of two calls. My solution can be made into a one-liner by writing the preg_ call inside of $lookup[ and ], but I'm aiming for readability.


p.s. Here is another variation that I dreamed up. The difference is that preg_match() always makes a match because of the final empty "alternative" (empty branch).

foreach ($tests as $test) {
preg_match('~(\p{Lu})|(\p{Ll})|~u', $test, $out);
echo "\n{$test}: " , $lookup[sizeof($out) - 1];
}

Check if char is the same as alphabet letter condition regardless of uppercase and lowercase | PHP & HTML

Create an array of valid characters all in the same case (upper in this case) and then compare the input, converted to upper with entries in the array

$character = 'd';

if ( in_array(strtoupper($character), ['A','B','C'] )) {
print "<p class='text-muted h4'> 2 - ABC</p>";
}

if ( in_array(strtoupper($character), ['D','E','F'] )) {
print "<p class='text-muted h4'> 3 - DEF</p>";
}
if ( in_array(strtoupper($character), ['G','H','I'] )) {
print "<p class='text-muted h4'> 4 - GHI</p>";
}
if ( in_array(strtoupper($character), ['J','K','L'] )) {
print "<p class='text-muted h4'> 5 - JKL</p>";
}
if ( in_array(strtoupper($character), ['M','N','O'] )) {
print "<p class='text-muted h4'> 6 - MNO</p>";
}

Check value if exist with uppercase and lowercase letters

 if( strtolower($row['username'])==strtolower($val['username']) ) { echo "Exists";}

You can also replace strtolower with strtoupper that will convert a string to upper case.

NOTE: That for this case strtolower and strtoupper will result in the same outcome as noted by @user3783243

Also if your trying to compare both values with Case Sensitivity that is you don't want if('JAck'== 'jAck') to return true then use strict comparison ===

 if('JAck'== 'jAck') //will return true
if('JAck'=== 'jAck') //will retrun false

Check if a String is ALL CAPS in PHP

Check whether strtoupper($str) == $str

To handle non-ascii use:

mb_strtoupper($str, 'utf-8') == $str

Count Uppercase and Lowercase Letters without using RegEx in php

$string    = "HelLo wOrlD";
$lowerCase = strtolower($string);
$upperCase = strtoupper($string);

$lowerDiff = similar_text($string, $lowerCase);
$upperDiff = similar_text($string, $upperCase);

echo "Capital:" . (strlen($string) - $lowerDiff); // 4
echo "<br>";
echo "Lowercase:" . (strlen($string) - $upperDiff); // 6

Check if string contains only lowercase letters and underscores

you can simply use:

/^[a-z_]+$/

For description and more examples you can visit here

PHP, how to check for uppercase/lowercase/numbers/special in regex

Depends on what specials. Can try this and use with preg_match.

preg_match('/^[[:alnum:][:punct:]]+$/', $str)

Check out demo at regex101

  • [:alnum:] matches [a-zA-Z0-9]
  • [:punct:] matches [!"#$%&'()*+,\-./:;<=>?@[\\\]^_{|}~] and backtick.
  • + one ore more from ^ start to $ end

See more posix classes



Related Topics



Leave a reply



Submit