Regular expressions (often called Regex) are sequences of characters that form a search pattern. They are used for complex string searching, validation (like emails), and advanced text manipulation.
A pattern can consist of a single character, or a more complicated template. Patterns are usually enclosed in delimiters, like forward slashes /.
Example pattern: /redohub/i (The i makes the search case-insensitive).
PHP uses the PCRE (Perl Compatible Regular Expressions) syntax. These are the most common functions:
preg_match()Checks if a pattern exists in a string. Returns 1 if found, 0 if not.
<?php
$str = "Visit RedoHub";
$pattern = "/redohub/i";
echo preg_match($pattern, $str); // Output: 1
?>
preg_match_all()Returns the number of times a pattern was found in the string.
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Output: 4
?>
preg_replace()Replaces matches with a new string.
<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "RedoHub", $str); // Output: Visit RedoHub!
?>
| Modifier | Description |
|---|---|
i | Performs a case-insensitive search. |
m | Performs a multiline search. |
u | Enables correct matching of UTF-8 encoded characters. |
strpos() or str_replace() as they are much faster.
/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/ for basic email validation.
/ to wrap your pattern.i for case-insensitive).preg_match() for existence checks.preg_replace() for complex pattern-based swaps.