How can I check if a char is a letter or a number?

纵然是瞬间 提交于 2019-11-30 03:57:44

问题


I have a string and I want to loop it so that I can check if every char is a letter or number.

$s = "rfewr545 345b";

for ($i=1; $i<=strlen($s); $i++){
   if ($a[$i-1] == is a letter){
      echo $a[$i-1]." is a letter";
   } else {
      echo $a[$i-1]." is a number";
   }
}

How can I check if a char is a letter or a number?


回答1:


To test if character is_numeric, use:

is_numeric($a[$i-1])

As below:

$s = "rfewr545 345b";
for ($i = 0; $i < strlen($s); $i++){
   $char = $s[$i];
   if (is_numeric($char)) {
      echo $char . ' is a number';
   } else {
      echo $char . ' is a letter';
   }
}



回答2:


You can use:

ctype_digit

and

ctype_alpha




回答3:


With regular expressions you can try the following.

Test for a number

if (preg_match('/\d/', $char)) :
     echo $char.' is a number';
endif;

Test for a "letter"

if (preg_match('/[a-zA-Z]/', $char)) :
     echo $char.' is a letter';
endif;

The benefit of this approach is mainly from the "letter" test, which lets you efficiently define what constitutes as a "letter" character. In this example, the basic English alphabet is defined as a "letter".




回答4:


See this: http://php.net/manual/en/function.is-numeric.php

if(Is_numeric($char)) {
//Do stuff
}
else {
//Do other stuff
}



回答5:


You can do by using is_numeric() function

if (is_numeric($a[$i-1])){
      echo $a[$i-1]." is a number";
   } else {
      echo $a[$i-1]." is a letter";
   }



回答6:


php provide some nice function to checkout chars. Use the apt functions as conditions in if blocks.

visit:

PHP char functions

e.g. ctype_digit returns true if number is numeric.




回答7:


You may use ctype_alpha to check for alphabetic character(s).

Similarly, you may use ctype_digit to check for numeric character(s).

is_numeric — Finds whether a variable is a number or a numeric string

is_numeric() example:

<?php

    $tests = array(
        "42",
        0b10100111001,
        "not numeric",
        array(),
        9.1
    );

    foreach ($tests as $element) {
        if (is_numeric($element)) {
            echo "'{$element}' is numeric", PHP_EOL;
        } else {
            echo "'{$element}' is NOT numeric", PHP_EOL;
        }
    }
?>

The above example will output:

'42' is numeric
'1337' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric

Where ctype_digit() and is_numeric() differ?

Example comparing strings with integers:

<?php
    $numeric_string = '42';
    $integer        = 42;

    ctype_digit($numeric_string);  // true
    ctype_digit($integer);         // false (ASCII 42 is the * character)

    is_numeric($numeric_string);   // true
    is_numeric($integer);          // true

?>


来源:https://stackoverflow.com/questions/14230986/how-can-i-check-if-a-char-is-a-letter-or-a-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!