Reputation: 369
How can I detect a non number or non letter on a string?
KY4R5EHCN5W476XXO5ER
- return true
KY4R5EHCN5W472X**@**O5ER
- return false
I know the answer is to use a regular expression, I just don't know how to do it. I suck at regular expressions. Any help will be appreciated.
Thanks!
Upvotes: -1
Views: 1735
Reputation: 5340
ctype_alnum() will be quite faster than a regular expression in detecting if a string is purely alpha-numeric (letters and numbers).
$str1 = 'KY4R5EHCN5W476XXO5ER';
$str2 = 'KY4R5EHCN5W472X*@*O5ER' ;
foreach (array($str1, $str2) as $str){
if (ctype_alnum($str)) {
echo "$str is alphanumeric\n" ;
}
else {
echo "$str is not just alphanumeric\n";
}
}
However, be sure to play with the regular expressions given here because it's a useful skill to have, especially if you later decide you also need to check for other characters like dashes. You will find The Regex Coach very useful when experimenting with them.
$str = 'KY4R5EHCN5W476XXO5ER' ;
$ut = microtime(true) ;
for ($i = 0 ; $i < 100000; $i++) {
$res = ctype_alnum($str) ;
}
$utCtype = microtime(true) ;
for ($i = 0 ; $i < 100000; $i++) {
$res = preg_match('/[a-z0-9]/i', $str) ;
}
$utEnd = microtime(true) ;
$utDiffCtype = $utCtype - $ut ;
$utDiffPreg = $utEnd - $utCtype;
echo "ctype: $utDiffCtype, preg: $utDiffPreg" ;
Upvotes: 1
Reputation: 59699
if (preg_match('/[^a-z0-9]/i', $subject)) {
// Invalid characters
} else {
// Only letters and numbers
}
Upvotes: 4
Reputation: 2180
(preg_match('/^[A-Z0-9]+$/', $string) == 0)
change to a-zA-Z0-9 if you want to include lowercase characters
this should return true if the string contains only A-Z and 0-9.
or
(preg_match('/[^A-Z0-9]/', $string) != 0)
should do pretty much the same.
Upvotes: 0
Reputation: 22152
You can use this:
if (preg_match('/^([a-z0-9]+)$/iu', $string))
{
// all alpha and digits
}
else
{
// not all alpha and digits
}
Upvotes: 0
Reputation: 360572
if (preg_match('/[^A-Z0-9]/', $string)) {
... some char other than A-Z, 0-9 detected
}
Upvotes: 4