PHP Regular Expressions (RegEx)
A Regular Expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.
1. Common Functions
PHP provides a set of functions that allow you to use regular expressions.
preg_match(): Returns 1 if the pattern was found in the string and 0 if not.preg_match_all(): Returns the number of times the pattern was found in the string.preg_replace(): Returns a new string where matched patterns have been replaced with another string.
2. Syntax
In PHP, regular expressions are strings composed of delimiters, a pattern, and optional modifiers.
$exp = "/w3schools/i";
/: Delimiterw3schools: Patterni: Modifier (case-insensitive)
3. Using preg_match()
The preg_match() function will tell you whether a string contains matches of a pattern.
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str); // Outputs 1
4. Using preg_replace()
The preg_replace() function will replace all of the matches of the pattern in a string with another string.
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "W3Schools", $str); // Outputs "Visit W3Schools!"
5. Common Metacharacters
^: Start of string$: End of string.: Any character\d: Digit\s: Whitespace[abc]: Find any character between the brackets