Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - regex to allow letters and numbers only

I have tried:

preg_match("/^[a-zA-Z0-9]", $value)

but im doing something wrong i guess.

like image 813
Jason94 Avatar asked Dec 03 '10 12:12

Jason94


3 Answers

1. Use PHP's inbuilt ctype_alnum

You dont need to use a regex for this, PHP has an inbuilt function ctype_alnum which will do this for you, and execute faster:

<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo "The string $testcase consists of all letters or digits.\n";
    } else {
        echo "The string $testcase does not consist of all letters or digits.\n";
    }
}
?>

2. Alternatively, use a regex

If you desperately want to use a regex, you have a few options.

Firstly:

preg_match('/^[\w]+$/', $string);

\w includes more than alphanumeric (it includes underscore), but includes all of \d.

Alternatively:

/^[a-zA-Z\d]+$/

Or even just:

/^[^\W_]+$/
like image 150
SW4 Avatar answered Oct 22 '22 00:10

SW4


You left off the / (pattern delimiter) and $ (match end string).

preg_match("/^[a-zA-Z0-9]+$/", $value)
like image 26
Kendall Hopkins Avatar answered Oct 22 '22 02:10

Kendall Hopkins


  • Missing end anchor $
  • Missing multiplier
  • Missing end delimiter

So it should fail anyway, but if it may work, it matches against just one digit at the beginning of the string.

/^[a-z0-9]+$/i
like image 14
KingCrunch Avatar answered Oct 22 '22 02:10

KingCrunch