Regex in PHP
Regular Expressions (RegEx) in PHP
Regular Expressions (RegEx) are a powerful tool used for pattern matching and text manipulation. In PHP, RegEx can be used for tasks like validating form inputs, searching and replacing text, and extracting specific patterns from strings.
PHP provides functions for working with regular expressions using the PCRE (Perl Compatible Regular Expressions) library, which is a powerful and flexible regular expression engine. PHP supports both POSIX and Perl-compatible syntax.
Basic Syntax of Regular Expressions
A regular expression (RegEx) is made up of a pattern that describes a set of strings. The pattern can include:
Literals (actual characters)
Metacharacters (special characters that have a specific meaning in RegEx)
Common Metacharacters:
.(dot): Matches any single character except newline.^: Asserts the position at the start of the string.$: Asserts the position at the end of the string.[]: Matches any one of the enclosed characters (e.g.,[a-z]).|: Logical OR, matches the pattern before or after the pipe.*: Matches 0 or more occurrences of the preceding element.+: Matches 1 or more occurrences of the preceding element.?: Matches 0 or 1 occurrence of the preceding element.()(parentheses): Groups patterns for capturing or applying quantifiers.\: Escapes metacharacters to match them literally (e.g.,\\matches a backslash).
Common PHP Functions for Regular Expressions
PHP provides two families of functions for working with RegEx:
Perl-compatible regular expressions (PCRE):
preg_*functions.POSIX-style regular expressions:
ereg_*functions (deprecated in PHP 5.3.0 and removed in PHP 7.0.0).
We'll focus on the more commonly used PCRE functions.
1. preg_match()
preg_match() searches for a pattern in a string and returns true if a match is found.
Syntax:
preg_match(pattern, string, matches, flags, offset);pattern: The regular expression pattern.
string: The string to search.
matches: (optional) An array that will hold the matched text.
flags: (optional) Modifiers that change the behavior of the regular expression (e.g.,
PREG_OFFSET_CAPTURE).offset: (optional) The position from which to start searching.
Example: Match an email address.
<?php$email = "test@example.com";$pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";if (preg_match($pattern, $email)) { echo "Valid email address!";} else { echo "Invalid email address.";}?>2. preg_match_all()
preg_match_all() is similar to preg_match(), but it returns all matches found in the string.
Syntax:
preg_match_all(pattern, string, matches, flags, offset);matches: An array that will hold the matches. It will contain the full matches and, if parentheses are used in the pattern, the sub-patterns.
Example: Find all email addresses in a string.
<?php$string = "Contact us at test@example.com or hello@domain.com.";$pattern = "/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/";preg_match_all($pattern, $string, $matches);print_r($matches[0]); // Prints all found email addresses?>3. preg_replace()
preg_replace() searches for a pattern and replaces it with a specified string.
Syntax:
preg_replace(pattern, replacement, string, limit, count);pattern: The regular expression pattern to search for.
replacement: The string to replace the matches with.
string: The string in which to perform the replacement.
limit: (optional) The maximum number of replacements to perform.
count: (optional) An integer variable that will be set to the number of replacements done.
Example: Replace all occurrences of "apple" with "orange".
<?php$string = "I like apple and apple pie.";$pattern = "/apple/";$newString = preg_replace($pattern, "orange", $string);echo $newString; // Output: I like orange and orange pie.?>4. preg_split()
preg_split() splits a string by a regular expression pattern.
Syntax:
preg_split(pattern, string, limit, flags);pattern: The regular expression pattern.
string: The string to split.
limit: (optional) The maximum number of elements to return.
flags: (optional) Flags to modify the behavior of the split (e.g.,
PREG_SPLIT_NO_EMPTY).
Example: Split a sentence into words.
<?php$string = "apple, orange, banana, grape";$pattern = "/,\s*/"; // Split by comma followed by optional space$words = preg_split($pattern, $string);print_r($words);?>5. preg_replace_callback()
preg_replace_callback() is similar to preg_replace(), but it uses a callback function to modify the matched text before replacing it.
Syntax:
preg_replace_callback(pattern, callback, string);pattern: The regular expression pattern.
callback: A callback function that takes the match and returns a modified value.
string: The string in which to perform the replacement.
Example: Add a prefix "Mr. " to all names.
<?php$string = "John, Jane, Bob";$pattern = "/\b(\w+)\b/";$callback = function($matches) { return "Mr. " . $matches[1];};$newString = preg_replace_callback($pattern, $callback, $string);echo $newString; // Output: Mr. John, Mr. Jane, Mr. Bob?>Modifiers in Regular Expressions
PHP supports several modifiers that can be added to the regular expression pattern to change how the pattern is matched.
i: Case-insensitive matching.m: Multiline matching. Treats the start (^) and end ($) of the string as working across lines.s: Dot matches all, including newlines (.will match any character, including line breaks).x: Allows whitespace and comments within the pattern for better readability.
Example: Case-insensitive match.
<?php$string = "Hello World!";$pattern = "/hello/i"; // Case-insensitive searchif (preg_match($pattern, $string)) { echo "Match found!";} else { echo "No match.";}?>PHP Regular Expression Example: Validating a Phone Number
Let's say you want to validate a phone number to ensure it matches a specific pattern (e.g., (123) 456-7890).
<?php$phone = "(123) 456-7890";$pattern = "/^\(\d{3}\) \d{3}-\d{4}$/"; // Matches (123) 456-7890if (preg_match($pattern, $phone)) { echo "Valid phone number.";} else { echo "Invalid phone number.";}?>Conclusion
Regular Expressions in PHP are a powerful tool for pattern matching, text validation, and manipulation. The preg_* functions provide robust support for performing complex text-processing tasks, from simple searches to intricate replacements. Understanding the syntax and functions available for RegEx in PHP can greatly enhance your ability to work with dynamic content and user input validation.
If you need more detailed explanations or examples on any specific topic within RegEx, feel free to ask!