54

I have tried:

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

but im doing something wrong i guess.

5 Answers 5

114

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_]+$/
4
  • 5
    [\w\d] is redundant - \w is enough since it already contains \d. Commented Nov 14, 2011 at 10:16
  • 2
    In the first example a + is missing, so it should be '/^[\w]+$/'.
    – mommi84
    Commented Mar 22, 2014 at 0:10
  • Added the missing + quantifier. Commented Nov 21, 2014 at 21:12
  • [\w] is more simply expressed as \w. Commented Nov 19, 2021 at 3:01
27

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

preg_match("/^[a-zA-Z0-9]+$/", $value)
1
  • This solution is not working on Turkish language characters. Thank you
    – Kamlesh
    Commented Sep 6, 2020 at 8:01
14
  • 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
3

As the OP said that he wants letters and numbers ONLY (no underscore!), one more way to have this in php regex is to use posix expressions:

/^[[:alnum:]]+$/

Note: This will not work in Java, JavaScript, Python, Ruby, .NET

-2

try this way .eregi("[^A-Za-z0-9.]", $value)

1
  • 4
    ereg/eregi are old functions. Use preg_match instead. Also, you should add the i identifier so letters are case insensitive.
    – ChrisH
    Commented Apr 20, 2012 at 9:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.