Character classes and quantifiers help you find patterns in text. They let you check if text matches certain rules.
0
0
Character classes and quantifiers in PHP
Introduction
Checking if a password has letters and numbers.
Finding all words that start with a capital letter.
Validating an email address format.
Extracting phone numbers from a message.
Replacing repeated spaces with a single space.
Syntax
PHP
/[character_class]{quantifier}/Character classes are inside square brackets [].
Quantifiers tell how many times the character or class should appear.
Examples
Matches any lowercase letter from a to z.
PHP
/[a-z]/
Matches one or more digits (0-9).
PHP
/\d+/
Matches exactly three uppercase letters in a row.
PHP
/[A-Z]{3}/Matches zero or one vowel (a, e, i, o, u).
PHP
/[aeiou]?/
Sample Program
This program finds a sequence of 3 or more digits in a string and prints it. Then it replaces multiple spaces with one space in another string.
PHP
<?php // Check if a string has 3 or more digits in a row $text = "My phone number is 123456."; if (preg_match('/\d{3,}/', $text, $match)) { echo "Found digits: " . $match[0] . "\n"; } else { echo "No match found.\n"; } // Replace multiple spaces with a single space $sentence = "This is a test."; $clean = preg_replace('/ +/', ' ', $sentence); echo $clean . "\n";
OutputSuccess
Important Notes
Use a backslash \ in PHP strings to write regex special characters like \d.
Quantifiers: * means 0 or more, + means 1 or more, ? means 0 or 1, {n} means exactly n times, {n,} means n or more times.
Summary
Character classes let you match groups of characters easily.
Quantifiers control how many times the pattern should appear.
Together, they help you find or change text that fits certain patterns.