I need a help with regex which checks the string contains only letter and numbers but not only numbers
Valid
* letters
* 1wret
* 0123chars
* chars0123
*
^[0-9]*[a-zA-Z]+[0-9a-zA-Z]*$
translated: from the beginning, match 0 or more numbers, then match at least one letter, then match zero or more letters or numbers until the end.
Here are the components of the regex we're going to use:
^
and $
are the beginning and end of the string anchors respectively\d
matches a digit[a-zA-Z]
matches a letter[a-zA-Z\d]
matches a letter or a digit*
is "zero-or-more" repetitionWith these, we can now compose the regex we need (see on rubular.com):
^\d*[a-zA-Z][a-zA-Z\d]*$
Here's an explanation of the pattern:
from the beginning... till the end
| |
^\d*[a-zA-Z][a-zA-Z\d]*$
\_/\______/\_________/
The 3 parts are:
Instead of using a regular expression, you can also use the ctype_*()
functions:
var_dump(ctype_alnum('letters') && !ctype_digit('letters')); // bool(true)
var_dump(ctype_alnum('0123chars') && !ctype_digit('0123chars')); // bool(true)
var_dump(ctype_alnum('1324') && !ctype_digit('1324')); // bool(false)
var_dump(ctype_alnum('xcvxxc%$#') && !ctype_digit('xcvxxc%$#')); // bool(false)
But if you want a regular expression, you can use this:
var_dump(preg_match('/^[a-z0-9]*[a-z]+[a-z0-9]*$/i', $input));
This should do it:
^[0-9]*[a-zA-Z]+[a-zA-Z0-9]*$
This requires at least one character of [a-zA-Z]
.
[a-z0-9]*[a-z]+[a-z0-9]*
^(?=.*[a-z])[a-zA-Z0-9]+$
(?=.*[a-z])
positive lookahead to make sure that there is at least one letter in the string (but doesn't consume any characters - gives up the matched characters as soon as it returns (in this case, as soon as it finds a letter)).[a-zA-Z0-9]+
make sure string contains only alphanumeric characters.^
and $
are start and end of string delimiters.