00 Votes

PHP: Test if string only contains numbers and letters

Question by Compi | 2012-08-22 at 13:11

I would like to check with PHP whether a string only consists of letters and numbers (digits). I have fished some solutions with regular expressions out of the Internet, but somehow I get them not running for me. Does anyone have a easy-to-use solution?

ReplyPositiveNegative
0Best Answer0 Votes

PHP provides a very useful feature, that allows you to check strings without formulating a regular expression. The function is called ctype_alnum():

$string1 = '123ABCabc';
$string2 = '123ABCabc!';
 
if (ctype_alnum($string1)) {
   // this code will be executed
}
 
if (!ctype_alnum($string2)) {
   / this code will be executed
}

If the string contains only numbers (digits) or letters (A-Z or a-z; umlauts are not considered as letters), ctype_alnum() returns true, otherwise false.

In the example, both codes will be executed, because once ctype_alnum() was negated.

Apart from ctype_alnum(), there are some further functions such as ctype_digit(), which returns true if the string contains only digits. An overview over all of this functions, I have introduced in my article Check Strings with Ctype-Functions for Character Classes.
2012-08-24 at 23:53

ReplyPositive Negative
Reply

Related Topics

HTACCESS: Simplify URL

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.