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

后端 未结 13 1121
忘了有多久
忘了有多久 2020-12-04 19:12

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?

相关标签:
13条回答
  • 2020-12-04 19:53

    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....
    }
    
    0 讨论(0)
  • 2020-12-04 19:55
    echo preg_match('~^\p{Lu}~u', $string_data) ? 'Upper' : 'lower';
    
    /** Please check below lines. I have elaborate above code. **/
    
    ~      ; start 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 match
    
    0 讨论(0)
  • 2020-12-04 19:55
    I think 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';
    

    /** Please check the below lines. I have elaborated above code. **/

    ~ ; start 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 match $dataArr = ['âa', 'Bbbbb', 'Éé', 'iou', 'Δδ'];

    foreach ($dataArr as $val) { echo "\n{$val}:"; echo "\n\tPREG: " , preg_match('~^\p{Lu}~u', $val) ? 'upper' : 'lower'; echo "\n\tCTYPE: " , ctype_upper(mb_substr($val, 0, 1)) ? 'upper' : 'lower'; echo "\n\t< a: " , mb_substr($val, 0, 1) < 'a' ? 'upper' : 'lower'; $char = mb_substr ($val, 0, 1, "UTF-8"); echo "\n\tMB: " , mb_strtoupper($char, "UTF-8") == $char? 'upper' : 'lower'; }

    This one is best. Just try it.

    0 讨论(0)
  • 2020-12-04 19:56

    Use ctype_upper for check upper case:

    $a = array("Word", "word", "wOrd");
    
    foreach($a as $w)
    {
        if(ctype_upper($w{0}))
        {
            print $w;
        }
    }
    
    0 讨论(0)
  • 2020-12-04 19:58

    Tried ?

    $str = 'the text to test';
    if($str{0} === strtoupper($str{0})) {
       echo 'yepp, its uppercase';
    }
    else{
       echo 'nope, its not upper case';
    }
    
    0 讨论(0)
  • 2020-12-04 20:05

    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
    }
    
    0 讨论(0)
提交回复
热议问题