Regular Expressions (RegEx) are sequences of characters that define a search pattern. They are an indispensable tool for complex string manipulation, far exceeding the capabilities of simple functions like str_replace() or strpos().
In PHP, Regular Expressions are handled by the PCRE (Perl Compatible Regular Expressions) functions, all of which start with preg_.
1. The Core RegEx Functions
You will primarily use these three functions in PHP:
| Function | Purpose |
preg_match() | Checks if a pattern exists in a string. Returns 1 (true) or 0 (false). |
preg_match_all() | Finds all occurrences of a pattern in a string and returns the count. |
preg_replace() | Searches for a pattern and replaces all occurrences with a replacement string. |
2. The RegEx Structure (Delimiters)
Every Regular Expression in PHP must be enclosed by delimiters. The forward slash (/) is the most common delimiter.
| Structure | Example | Description |
'/pattern/' | '/php/i' | The pattern is php. The / characters are the delimiters. |
3. Basic Search Example (preg_match())
This function is essential for quick validation, such as checking if a form field contains only letters.
<?php
$pattern = "/php/";
$text = "I love the PHP programming language.";
// Check if the pattern "php" exists in the string
if (preg_match($pattern, $text)) {
echo "Match found!";
} else {
echo "No match found.";
}
// Output: Match found!
?>
4. Metacharacters (The Power of Patterns)
Metacharacters are special characters that give RegEx its power by allowing you to define complex rules.
| Metacharacter | Description | Example Pattern | Matches |
^ | Starts with (beginning of string). | '/^Hello/' | A string that begins with “Hello”. |
$ | Ends with (end of string). | '/World$/' | A string that ends with “World”. |
[abc] | Character classes (any one character listed). | '/[aeiou]/' | Any single lowercase vowel. |
[0-9] | Range of characters (any digit). | '/[a-z]/' | Any single lowercase letter. |
| **` | `** | OR operator (either/or). | `’/red |
() | Grouping of expressions. | '(apple)s?' | Matches “apple” or “apples”. |
Example: Basic Email Validation Check
This example uses ^ (start), @ (literal), and $ (end) to ensure the string looks like an email.
<?php
$pattern = "/^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$/";
$email = "test.user@example.com";
if (preg_match($pattern, $email)) {
echo "Email format is valid.";
} else {
echo "Email format is NOT valid.";
}
?>
5. Quantifiers (How Many Times?)
Quantifiers specify how many instances of the preceding character, metacharacter, or group must be present for a match to occur.
| Quantifier | Description | Example Pattern | Matches |
+ | One or more occurrences. | '/a+/' | ‘a’, ‘aa’, ‘aaa’, etc. |
* | Zero or more occurrences. | '/b*/' | ”, ‘b’, ‘bb’, ‘bbb’, etc. |
? | Zero or one occurrence. | '/colou?r/' | ‘color’ or ‘colour’. |
{n} | Exactly n occurrences. | '/a{3}/' | ‘aaa’. |
{n,} | At least n occurrences. | '/a{2,}/' | ‘aa’, ‘aaa’, ‘aaaa’, etc. |
{n,m} | Between n and m occurrences. | '/a{2,4}/' | ‘aa’, ‘aaa’, or ‘aaaa’. |
Example: Password Strength Check
Check for a password between 8 and 15 characters that contains only letters and numbers.
<?php
// Pattern: Start of string (^), 8 to 15 alphanumeric chars ([a-zA-Z0-9]{8,15}), end of string ($)
$password_pattern = '/^[a-zA-Z0-9]{8,15}$/';
$password = "Secret2025";
if (preg_match($password_pattern, $password)) {
echo "Password length and characters are acceptable.";
}
?>
6. Replacing Text (preg_replace())
The preg_replace() function is much more powerful than str_replace() because it can replace patterns instead of just fixed strings.
| Syntax | Description |
preg_replace(pattern, replacement, subject) | Searches the subject string for the pattern and replaces it with the replacement string. |
Example: Removing HTML Tags
<?php
// Pattern: Find any HTML tag (< followed by anything, followed by >)
$pattern = '/<.*?>/';
$text_with_tags = "<h1>Title</h1><p>Some text.</p>";
// Replace all tags with an empty string
$clean_text = preg_replace($pattern, '', $text_with_tags);
echo $clean_text;
// Output: TitleSome text.
?>
You have now covered all fundamental elements of procedural PHP (Syntax, Data Types, Logic, Arrays, Strings, Numbers, Dates, Constants, Forms, DB interaction, and RegEx).
The curriculum is now ready to move into the advanced, modern programming paradigm essential for professional development.
