Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 802
gadss Avatar asked Jan 09 '13 08:01

gadss


2 Answers

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".

like image 125
Boaz Avatar answered Oct 14 '22 11:10

Boaz


You can use:

ctype_digit

and

ctype_alpha

like image 29
codaddict Avatar answered Oct 14 '22 11:10

codaddict