php-regexHow to use PHP regex to match letters, numbers and underscores?
Using PHP regex to match letters, numbers and underscores is a common task. The following example code block shows how to do this:
$string = 'abc123_ABC';
$pattern = '/^[a-zA-Z0-9_]+$/';
if (preg_match($pattern, $string)) {
echo 'Matched!';
} else {
echo 'Not matched!';
}
The output of the example code is:
Matched!
Code explanation
$string = 'abc123_ABC';
: This is the string to be tested.$pattern = '/^[a-zA-Z0-9_]+$/';
: This is the regular expression pattern used to match letters, numbers and underscores. The pattern/^[a-zA-Z0-9_]+$/
means that the string should start with a letter, number or underscore, and end with a letter, number or underscore.preg_match($pattern, $string)
: This is the function used to match the string against the pattern.if (preg_match($pattern, $string)) {
: This is the condition used to check if the string matches the pattern.echo 'Matched!';
: This is the output if the string matches the pattern.echo 'Not matched!';
: This is the output if the string does not match the pattern.
Helpful links
More of Php Regex
- How to get the first match when using regex in PHP?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match a zip code?
- How to use PHP regex to match special characters?
- How to use PHP regex to match an exact string?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match URL path?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match a year?
See more codes...