I have tried:
preg_match("/^[a-zA-Z0-9]", $value)
but im doing something wrong i guess.
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";
}
}
?>
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_]+$/