Regular Expressions, commonly known as the “regex” or “RegExp,” are specially formatted text strings used to detect patterns in text. Regular expressions are one of the various robust tools available today for effective and efficient text processing and manipulations.
Why use regular expressions
- Regular expressions simplify identifying patterns in the string data by calling the single function. It preserves the coding time.
- It is useful when we are validating the user input such as email address, domain names, telephone numbers, IP addresses.
- Highlighting keywords in search outcomes.
- When creating a custom HTML template, the regular expressions can be used to recognize the template tags and replace them with actual data.
PHP Regular Expression
PHP version 5.3 and above supports the Perl style regular expressions via its preg_ family of functions.
We use Perl style regular expressions because Perl (Practical Extraction and Report Language) was the first mainstream programming language that provided interracial support for the regular expressions and it is well known for its strong support of the regular expressions and its extraordinary text processing and manipulation capabilities.
PHP language has built-in functions that allow us to work with regular functions. Let’s now look at the regularly used regular expression functions in PHP.
- preg_match – The preg_match() function is used to perform the pattern match on a string. It returns true if the match is found and false if the match is not found.
- preg_split – The preg_split() function is used to perform the pattern match on a string and then split the results into the numeric array.
- preg_replace – The preg_replace() function is used to perform the pattern match on the string and then replace the match with a specified text.
PHP preg_match()
The preg_match() function searches string for a pattern, returning true if a pattern exists, and false otherwise. If the optional input parameter pattern_array is provided, then pattern_array will contain various sections of the subpatterns included in the search pattern, if applicable.
Typically, the search starts from the beginning of the subject string. An optional parameter offset can be used to specify the alternate place from which to start the search.
See the following syntax for preg_match() function.
preg_match( $pattern, $input, $matches, $flags, $offset )
The preg_match() function accepts five parameters.
- pattern: The pattern parameter contains the pattern to search for, as a string.
- input: The input parameter contains the input string.
- matches: If the matches exist, then it contains results of the search. The $matches[0] will hold the text that matched the full pattern, $matches[1] will hold the text that matched the first captured parenthesized subpattern, and so on.
- flags: There are the following flags:
- PREG_OFFSET_CAPTURE: If the PREG_OFFSET_CAPTURE flag is passed as a parameter, for every match an append string offset will be returned as an output.
- PREG_UNMATCHED_AS_NULL: If the PREG_UNMATCHED_AS_NULL flag is passed as a parameter then, the subpatterns which are not matched reports as NULL; otherwise they report as the empty string.
- Offset: Usually, the search starts from the start of the input string. The offset optional parameter offset is used to specify the place from where to start the search (in bytes).
See the following example.
<?php // app.php $uniform = "https://appdividend.com"; if (preg_match("/appdividend/", $uniform)) { echo "URL $uniform contains AppDividend"; } else { echo "URL $uniform does not contain AppDividend"; }
In the above example,
- “preg_match(…)” is the PHP regular expression function.
- “/appdividend/” is the regular expression pattern to be matched.
- “$uniform” is the variable containing the text to be matched against.
See the following output.
➜ pro php app.php URL https://appdividend.com contains AppDividend ➜ pro
PHP preg_split()
The preg_split() function is the inbuilt function in PHP which is used to transform the given string into an array. The function divides the string into the smaller strings or sub-strings of length, which is specified by the user. If the limit is specified, then the small string or sub-strings up to limit return through an array.
Syntax
See the following syntax.
preg_split($pattern, $subject, $limit, $flag)
Parameters
- $pattern: The value is string type in which the pattern is to search as the string; otherwise its departs the items.
- $subject: The $subject parameter is variable, which is used to save the input string.
- $limit: The $limit indicates the limit. If the limit is specified, then the small or sub-string to be returned up to the limit. If the limit is 0 or -1, it indicates “no limit” later used by flag ($strflag).
- $flags: The $flags are used for signalizing and its variable type used to register two states True or False to control a program. Its combinations of the different flags such as below:
- PREG_SPLIT_NO_EMPTY: If the flag variable is set to PREG_SPLIT_NO_EMPTY, then only non-empty pieces will be returned by the preg_split() function.
- PREG_SPLIT_DELIM_CAPTURE: If the flag variable is set to this parameter then, the parenthesized expression in the delimiter pattern will be apprehended and returned as well.
- PREG_SPLIT_OFFSET_CAPTURE: If the flag variable is set to the PREG_SPLIT_OFFSET_CAPTURE, for each occurring match an appendant string offset will be returned and changes the return value in an array where matched string offset will be 0 and input string offset will be 1.
See the following example.
<?php // app.php $str = 'MillieBobbyBrown'; $outcome = preg_split('//', $str , -1, PREG_SPLIT_NO_EMPTY); print_r($outcome);
The above code returns the array after the divided boundaries matched. When the limit of an original array or string exceeds then returns with the array item otherwise, it’s False.
See the output.
➜ pro php app.php Array ( [0] => M [1] => i [2] => l [3] => l [4] => i [5] => e [6] => B [7] => o [8] => b [9] => b [10] => y [11] => B [12] => r [13] => o [14] => w [15] => n ) ➜ pro
Let’s split the strings when we find the spaces between the substrings.
<?php // app.php $outcome = preg_split("/[\s,]+/", "Millie Bobby Brown"); print_r($outcome);
See the output.
➜ pro php app.php Array ( [0] => Millie [1] => Bobby [2] => Brown ) ➜ pro
#PHP preg_replace() Example
The preg_replace() function is the inbuilt function in PHP which is used to perform the regular expression for search and replace the content.
See the following syntax.
preg_replace($pattern, $replacement, $subject, $limit, $count)
- $pattern: The $patten parameter contains the string item which is used to search the content, and it can be the string or an array of string.
- $replacement: The $replacement the mandatory parameter which specifies the string or an array with strings to replace.
- $subject: The $subject parameter is a string or an array with strings to search and replace.
- $limit: The $limit parameter specifies the maximum possible replacements for each pattern.
- $count: The $count parameter is an optional parameter. The $count variable will be filled with the number of replacements done.
See the following example.
<?php // app.php $string = 'February 19, 2004'; $pattern = '/(\w+) (\d+), (\d+)/i'; $replacement = '${1} 29, $3'; echo preg_replace($pattern, $replacement, $string);
See the following output.
➜ pro php app.php February 29, 2004 ➜ pro
The PHP preg_replace() function returns an array if the subject parameter is an array, or a string otherwise.
Finally, PHP Regular Expression Example is over.