PHP Regex Character Classes 🎯

beginner
19 min

PHP Regex Character Classes 🎯

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!

What are Character Classes? πŸ“

Character Classes in PHP Regular Expressions allow you to match any character from a specific set. They are enclosed within square brackets [].

Basic Character Classes πŸ“

The simplest character class matches a single character. Here's an example:

php
$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'.

Range of Characters πŸ“

You can also specify a range of characters in a character class. For example:

php
$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.

Special Characters in Character Classes πŸ’‘

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:

php
$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.

Negated 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:

php
$text = "Hello World!"; $pattern = "/[^!]/"; if (preg_match_all($pattern, $text, $matches)) { print_r($matches[0]); }

In this example, the pattern /[^!]/ matches any character except '!'.

Character Classes and Quantifiers πŸ’‘

Just like regular expressions, you can use quantifiers with character classes to match multiple characters. Here's an example:

php
$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.

Practice 🎯

Quick Quiz
Question 1 of 1

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! πŸŽ‰