2012-03-30 69 views
1

我有一個PHP兩個字符串我想讓以下檢查在分化字母數字和字母在PHP

1) 4f74adce2a4d2  - contains ***alphanumerics*** 

2) getAllInfo   - contains ***only alphabetic*** 

檢查這個我寫了一個功能,但任何價值$ PK包含上述中,成果轉化 如此而已,但i want to differentiate between alphanumeric and alphabetic only

<?php 
if (ereg('[A-Za-z^0-9]', $pk)) { 
    return true; 
} else if (ereg('[A-Za-z0-9]', $pk)) { 
    return false; 
} 
?> 
+4

你也可以看看這個擴展:http://php.net/ctype – mishu 2012-03-30 14:57:33

+1

al所以pcre建議http://php.net/pcre – mishu 2012-03-30 14:59:01

+1

擴大點@mishu使這些ctype功能看起來更具體http://www.php.net/manual/en/function.ctype-alnum.php http://www.php.net/manual/en/function.ctype-alpha.php – martynthewolf 2012-03-30 15:01:03

回答

3

使用以下兩個函數來檢測變量是否爲alhpanumeric或字母:

// Alphabetic 
if(ctype_alpha($string)){ 
    // This is Alphabetic 
} 

// Alphanumeric 
if(ctype_alnum($string)){ 
    // This is Alphanumeric 
} 

訪問此鏈接的參考指南:用於字母http://php.net/manual/en/book.ctype.php

0

對於aphanumeric:

function isAlphaNumeric($str) { 
    return !preg_match('/[^a-z0-9]/i', $str); 
} 

僅限字母:

function isAlpha($str) { 
    return !preg_match('/[^a-z]/i', $str); 
} 
+1

爲什麼不只是'返回preg_match('/ [a-zA-Z] /',$ str)'?另外,當我們有'i'說明符時,爲什麼還要在一個組中定義大寫和小寫字符? – J0HN 2012-03-30 15:00:50

+0

我已經添加了'i'說明符。返回preg_match將正常工作(在它之前有一個'!',所以如果它找到不是字母/字母數字的字符,它將返回false)。 – 2012-03-30 15:06:20

+0

是的,但負面小組賽比正面表現較差。所以你的解決方案是正確的,但具有較小的性能。 – J0HN 2012-03-30 15:10:50

2

如果您放置一個插入符(^),除了它當作普通字符中第一個字符組([])內的任意位置。所以,你的第一個正則表達式匹配甚至

466^qwe^aa 
11123asdasd^aa 
aaa^aaa 
^^^ 

這不是我的意圖。只要刪除插入符號和0-9,所以你的第一個正則表達式只是[A-Za-z]。這意味着'匹配任何字符,沒有別的'。

UPDATE另外,如Ben Carey指出,使用內置的ctype擴展可以實現相同的效果。

+0

這是正確的,但爲什麼在內置插件時使用自定義函數? – 2012-03-30 15:05:47

+0

@Ben,你可能會錯過答案。我沒有使用任何自定義功能:) – J0HN 2012-03-30 15:08:42

+0

你已經正確回答了這個問題,但是我唯一的評論就是,你還沒有建議一個更簡單的選項。以上是正確的,但如果他使用ctype擴展名,解決方案會更容易。你不同意嗎? – 2012-03-30 15:11:40

2

Unicode屬性是\pL和用於數字\pN

if (preg_match('/^\pL+$/', $pk) return true; // alphabetic 
if (preg_match('/^[\pL\pN]+$/', $pk) return false; // alphanumeric