Welcome to the PHP Regex Character Classes tutorial! In this lesson, we'll delve into one of the most powerful features of PHP regular expressions - Character Classes. Let's get started!
Character Classes in PHP Regular Expressions allow you to match any character from a specific set. They are enclosed within square brackets [].
The simplest character class matches a single character. Here's an example:
$text = "Hello World";
$pattern = "/H/";
if (preg_match($pattern, $text)) {
echo "Match found!";
}In this example, the pattern /H/ matches the first character 'H' in the string 'Hello World'.
You can also specify a range of characters in a character class. For example:
$text = "Apple, Orange, Banana";
$pattern = "/[A-Za-z]/";
if (preg_match_all($pattern, $text, $matches)) {
print_r($matches[0]);
}In this example, the pattern /[A-Za-z]/ matches any uppercase or lowercase alphabet in the given string.
Some characters have special meanings inside character classes, and to match them literally, you need to escape them with a backslash \. Here are some examples:
$text = "ABC123!@#";
$patterns = [
"/[0-9]/", // Matches any digit (0-9)
"/[!@#]/", // Matches !, @, or #
];
foreach ($patterns as $pattern) {
if (preg_match($pattern, $text)) {
echo "Match found: " . $pattern . PHP_EOL;
}
}In this example, the special characters 0-9, !, @, and # are matched using character classes.
To match any character except those in a set, you can use a ^ character at the beginning of the character class. Here's an example:
$text = "Hello World!";
$pattern = "/[^!]/";
if (preg_match_all($pattern, $text, $matches)) {
print_r($matches[0]);
}In this example, the pattern /[^!]/ matches any character except '!'.
Just like regular expressions, you can use quantifiers with character classes to match multiple characters. Here's an example:
$text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$pattern = "/[A-Z]{3}/";
if (preg_match_all($pattern, $text, $matches)) {
print_r($matches[0]);
}In this example, the pattern /[A-Z]{3}/ matches any sequence of three alphabets.
What does the pattern `/[0-9]/` match in the string `"123ABC"`?
This is just a taste of what you'll learn in this tutorial. Stay tuned for more advanced examples and exercises! In the next part, we'll dive deeper into character classes and learn about special character class sequences.
Happy coding! π