Hunt
Hunt

Reputation: 8435

differentiate alphanumeric and alphabetic in php

i have two strings in a php i want to make following checks in that

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

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

to check this i wrote a function but whatever value $pk contains among above , results into true only , but 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;
}
?>

Upvotes: 1

Views: 409

Answers (4)

Toto
Toto

Reputation: 91518

Unicode properties for letters is \pL and for numbers \pN

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

Upvotes: 2

J0HN
J0HN

Reputation: 26961

If you place a caret (^) anywhere inside the group ([]) except the very first character it's treated as ordinary char. So, your first regex matches even

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

Which is not intended I think. Just remove the caret and 0-9, so your first regex is just [A-Za-z]. That mean 'match any character and nothing else'.

UPDATE Also, as Ben Carey pointed out, the same can be achieved using built-in ctype extension.

Upvotes: 2

Ben Carey
Ben Carey

Reputation: 16968

Use the following two functions to detect whether a variable is alhpanumeric or alphabetic:

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

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

Visit this link for the reference guide: http://php.net/manual/en/book.ctype.php

Upvotes: 3

Mircea Soaica
Mircea Soaica

Reputation: 2817

For aphanumeric:

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

For alphabetic only:

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

Upvotes: 0

Related Questions