Character classes
Learn to narrow patterns with character classes like \d, \w, \s and [a-z].
Character classes: [a-z] and \d
To match any character from a set, use a character class written inside square brackets: [aeiou] matches any vowel.
A hyphen gives a range: [a-z] lowercase letters, [0-9] digits. A ^ at the start means not: [^0-9] matches anything that is not a digit.
There are shortcuts too: \d = [0-9], \w = [a-zA-Z0-9_], \s whitespace. The uppercase forms (\D, \W, \S) are the negated versions.
Ranges and negation
Inside a character class, a hyphen (-) specifies a range. [0-9] is one digit, [A-Fa-f0-9] is one hexadecimal digit.
If the first character is ^, the class is negated: [^0-9] matches any single character that is not a digit. A ^ not at the start is treated as a literal.
To match a literal hyphen, put it at the start or end of the class: [-a] or [a-].
Exercise Only letters and digits?
Write isAlphanumeric(string $str): bool. Using the pattern /^[a-zA-Z0-9]+$/, return true if the string contains only letters and digits, false otherwise. Compare the preg_match result with === 1. The three echo calls below are already written; they print results for "PHP8", "PHP 8" and "PHP-8".
Show example solution
bool { return preg_match("/^[a-zA-Z0-9]+$/", $str) === 1; }
Example solution:
<?php
// isAlphanumeric: only letters and digits?
// Use a [a-zA-Z0-9] pattern with preg_match
// Define the isAlphanumeric function
function isAlphanumeric(string $str): bool {
return preg_match("/^[a-zA-Z0-9]+$/", $str) === 1;
}
echo isAlphanumeric("PHP8") ? "yes\n" : "no\n";
echo isAlphanumeric("PHP 8") ? "yes\n" : "no\n";
echo isAlphanumeric("PHP-8") ? "yes\n" : "no\n";
Test yourself
-
Understand the shortcuts
- \d
- Digit
- \w
- Word character
- \s
- Whitespace
- \D
- Non-digit
- [a-z]
- Lowercase range
-
What does [a-z] match?
- Only the letters 'a' and 'z'
- Both uppercase and lowercase letters
- Digits
- One lowercase letter from a to z
Show answer
One lowercase letter from a to z — Correct. [a-z] matches one lowercase letter between a and z.
-
Add a digit range
$pattern = "/[____]+/"; preg_match($pattern, "Tel: 0555", $matches);Show answer
$pattern = "/[0-9]+/"; preg_match($pattern, "Tel: 0555", $matches);