2013-01-09 72 views
5

我有一個字符串,我想循環它,以便我可以檢查每個字符是否是字母或數字。如何檢查字符是字母還是數字?

$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"; 
    } 
} 

如何檢查字符是字母還是數字?

+0

是否有可能對整個字符串,而不是遍歷每個字符使用正則表達式? –

+0

檢查http://stackoverflow.com/q/9721636/1169798和http://php.net/manual/en/function.is-numeric.php – Sirko

+0

'is_numeric()'應該做檢查數字的技巧。 – tradyblix

回答

9

要測試字符is_numeric,使用方法:

is_numeric($a[$i-1]) 

如下:

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

並非每個不是數字的字符都是一個字母! – m4t1t0

+0

這是op的情況。 – hsz

+0

多字節字符呢? –

0

見這樣的:通過使用is_numeric()來功能

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

你可以這樣做。

試了數

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

試了「信」

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

這種方法的好處主要是從「信」的測試,有效地讓你定義什麼構成作爲「字母」字符。在這個例子中,基本的英文字母被定義爲「字母」。

2

使用正則表達式,你可以嘗試以下 http://php.net/manual/en/function.is-numeric.php

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

preg_match('/^[a-zA-Z \ s \,] + $ /') –

+0

我相信OP指的是測試一個*字母*字符,而不是*字*。 – Boaz

+0

okok所以他正在循環 –

0

php提供了一些很好的功能來檢出字符。使用apt函數作爲if塊中的條件。

,請訪問:

PHP char functions

例如ctype_digit如果數字是數字,則返回true。

0

您可以使用ctype_alpha檢查字母字符。

同樣,您可以使用ctype_digit來檢查數字字符。

is_numeric - 檢測變量是否是一個數字或數字串

is_numeric()例如:

<?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; 
     } 
    } 
?> 

上例將輸出:

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

ctype_digit()is_numeric()不同?

實例比較字符串與整數:

<?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 

?> 
相關問題