Using the PHP Function Preg_Match to Search For Regular Expressions
The php function preg_match is a powerful tool for working with regular expression style patterns. It accepts two input parameters: the pattern enclosed in forward slashes and the string to search within. The function returns an integer value if it finds a match, or false on failure.
The function will search for the pattern in your string and return either 1 if the pattern found or 0 if it didn't find anything. It can also be used to set an alternate place in the string from which the search should start, using the optional parameter offset. This is especially useful for when you want to search in a specific direction in the string and don't want to do a global search.
You can also use a special preg_replace_callback function to do string substitution after the match is complete. This will use the array $m, which contains various sections of the matched subpatterns. For example, $m[0] will contain the overall match, $m[1] will contain the first captured parenthesized subpattern, and so on.
In this article we will be using the capturing groups feature of preg_match to search for the words "brown" and "fox" in a given string. The resulting matches will be stored in an array called $matches, and can then be accessed and displayed.
To do this we will be passing the pattern '/glad/' and the flag value PREG_OFFSET_CAPTURE to preg_match. This will cause it to capture every single occurrence of the full pattern, so the matches array will have elements at $matches[0] containing the matching text, $matches[1] containing the first captured parenthesized subpattern, etc.