This article provides a detailed analysis on how to use regular expressions for search replacement in PHP. For more information, see
1. preg_match-execute a regular expression to match
Int preg_match (string $ pattern, string $ subject [, array & $ matches [, int $ flags = 0 [, int $ offset = 0])
Search for a match between the regular expression specified by subject and pattern.
Pattern:
The pattern to be searched, string type.
Subject:
Input string.
Matches:
If the matches parameter is provided, it is filled with search results. $ Matches [0] will contain the text matched in full mode, $ matches [1] will contain the text matched by the first capture sub-group, and so on.
Flags:
Flags can be set to the following flag values: PREG_OFFSET_CAPTURE if this flag is passed, a string offset (relative to the target string) will be appended to each occurrence of matching results ). Note: this will change the padding to the array of the matches parameter and make each element a matched string from 0th elements, the first element is the offset of the matched string in the target string subject.
Offset:
Generally, the search starts from the starting position of the target string. The optional parameter offset is used to specify a search starting from an unknown target string (in bytes ).
Return value:
Preg_match () returns the matching times of pattern. Its value will be 0 (not matched) or 1 time, because preg_match () will stop searching after the first match. Different from this, preg_match_all () searches for subject until it reaches the end. If an error preg_match () occurs, FALSE is returned.
Example:
The code is as follows:
/*
* The "I" mark after the mode separator is a case-insensitive search.
* Output: 1
*/
Echo preg_match ("/, \ s * (php)/I", "In my point, PHP is the web scripting language of choice .");
Echo"
"." \ N ";
/*
* Output: Array ([0] =>, PHP [1] => PHP)
*/
$ Matches = array ();
Preg_match ("/, \ s * (php)/I", "In my point, PHP is the web scripting language of choice. I love php", $ matches );
Print_r ($ matches );
Echo"
"." \ N ";
/*
* Output: Array ([0] => Array ([0] =>, PHP [1] => 11) [1] => Array ([0] => PHP [1] => 13 ))
*/
Preg_match ("/, \ s * (php)/I", "In my point, PHP is the web scripting language of choice. I love php", $ matches, PREG_OFFSET_CAPTURE );
Print_r ($ matches );
Echo"
"." \ N ";
/*
* Output: Array ([0] => Array ([0] => e php [1] = 63) [1] => Array ([0] => php [1] => 65 ))
*/
Preg_match ("/[, a-z]? \ S * (php)/I "," In my point, PHP is the web scripting language of choice. I love php ", $ matches, PREG_OFFSET_CAPTURE, 28 );
Print_r ($ matches );
Echo"
"." \ N ";
?>
2. preg_match_all-execute a global regular expression to match
Int preg_match_all (string $ pattern, string $ subject [, array & $ matches [, int $ flags = PREG_PATTERN_ORDER [, int $ offset = 0])
Search all matching results of the regular expression specified by pattern in subject and output them to matches in the order specified by flag. after the first match is found, the child sequence continues searching from the last matched position.
Pattern:
The pattern to be searched, in the string format.
Subject:
Input string.
Matches:
Multi-dimensional arrays are used as output parameters to output all matching results. The array sorting is specified by flags.
Flags:
You can use the following tags (note that PREG_PATTERN_ORDER and PREG_SET_ORDER cannot be used at the same time). If no sorting tag is given, set it to PREG_PATTERN_ORDER:
PREG_PATTERN_ORDER:
The results are sorted as $ matches [0] to save all matches in the full mode, $ matches [1] to save all matches in the first subgroup, and so on.
PREG_SET_ORDER:
The result is sorted as $ matches [0] and contains all matching results (including sub-groups) after the first match. $ matches [1] contains all matching results (including sub-groups) after the second match) and so on.
PREG_OFFSET_CAPTURE:
If this flag is passed, the offset relative to the target string is increased when each detected match is returned. Note that this will change each matching result string element in matches and make it a 0th element as the matching result string, and the 1st element as the offset of the matching result string in the subject.
Return value:
Returns the number of complete matches (which may be 0), or returns FALSE if an error occurs.
Example:
The code is as follows:
/*
* Output: 2
*/
Echo preg_match_all ("/php/I", "In my point, PHP is the web scripting language of choice. I love php", $ matches );
Echo"
"." \ N ";
/*
* Output: Array ([0] =>, PHP [1] => PHP)
*/
$ Matches = array ();
Preg_match ("/[, a-z]? \ S * (php)/I "," In my point, PHP is the web scripting language of choice. I love php ", $ matches );
Print_r ($ matches );
Echo"
"." \ N ";
/*
* Output: Array ([0] => Array ([0] =>, PHP [1] => e php) [1] => Array ([0] => PHP [1] => php ))
*/
$ Matches = array ();
Preg_match_all ("/[, a-z]? \ S * (php)/I "," In my point, PHP is the web scripting language of choice. I love php ", $ matches, PREG_PATTERN_ORDER );
Print_r ($ matches );
Echo"
"." \ N ";
/*
* The output will be: Array ([0] => Array ([0] => Array ([0] =>, PHP [1] => 11) [1] => Array ([0] => PHP [1] => 13 )) [1] => Array ([0] => Array ([0] => e php [1] => 63) [1] => Array ([0] => php [1] => 65 )))
*/
$ Matches = array ();
Preg_match_all ("/[, a-z]? \ S * (php)/I "," In my point, PHP is the web scripting language of choice. I love php ", $ matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE );
Print_r ($ matches );
Echo"
"." \ N ";
/*
* Array ([0] => Array ([0] => e php [1] => 63) [1] => Array ([0] => php [1] => 65 ))
*/
$ Matches = array ();
Preg_match_all ("/[, a-z]? \ S * (php)/I "," In my point, PHP is the web scripting language of choice. I love php ", $ matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE, 28 );
Print_r ($ matches );
Echo"
"." \ N ";
?>
3. preg_split-use a regular expression to separate strings
Array preg_split (string $ pattern, string $ subject [, int $ limit =-1 [, int $ flags = 0])
Use a regular expression to separate a given string.
Pattern:
The search mode, in the string format.
Subject:
Input string
Limit:
If this parameter is specified, only limit substrings are allowed to be separated. The last substrings returned will contain all the remaining parts. When the limit value is-1, 0 or null, it indicates "unlimited". as the php standard, you can skip the flags setting using null.
Flags:
Flags can be any combination marked below (bitwise OR operation | combination ):
PREG_SPLIT_NO_EMPTY:
If this flag is set, preg_split () returns the non-empty part after the separator.
PREG_SPLIT_DELIM_CAPTURE:
If this flag is set, the parentheses expression in the separator mode will be captured and returned.
PREG_SPLIT_OFFSET_CAPTURE:
If this flag is set, a string offset will be appended to each returned matching result. note: this will change every element in the returned array and make each element a substring separated by 0th elements, the first element is an array composed of the offsets of the substring in the subject.
Return value:
Returns an array consisting of substrings separated by the pattern boundary.
Example:
The code is as follows:
/*
* The output is as follows:
* Array ([0] => In my point, [1] => is the web scripting language of choice. I love [2] =>)
*/
$ Matches = array ();
Print_r (preg_split ("/php/I", "In my point, PHP is the web scripting language of choice. I love php "));
Echo"
"." \ N ";
/*
* The output is as follows:
* Array ([0] => In my point, [1] => is the web scripting language of choice. I love php)
*/
$ Matches = array ();
Print_r (preg_split ("/php/I", "In my point, PHP is the web scripting language of choice. I love php", 2 ));
Echo"
"." \ N ";
/*
* The output is as follows:
* Array ([0] => In my point, [1] => is the web scripting language of choice. I love)
*/
$ Matches = array ();
Print_r (preg_split ("/php/I", "In my point, PHP is the web scripting language of choice. I love php",-1, PREG_SPLIT_NO_EMPTY ));
Echo"
"." \ N ";
?>
4. preg_quote-escape regular expression characters
String preg_quote (string $ str [, string $ delimiter = NULL])
Preg_quote () requires the str parameter and adds a backslash before the characters in each regular expression syntax. This is usually used when some runtime strings need to be matched as regular expressions.
Special characters in a regular expression include:. \ + *? [^] $ () {}=! <> | :-
Str:
Input string
Delimiter:
If the optional parameter delimiter is specified, it is also escaped. This is usually used to escape the separator used by the PCRE function. /Is the most common delimiter.
Return value:
Returns the escaped string.
Example:
The code is as follows:
// In this example, preg_quote ($ word) is used to maintain the meaning of the asterisk in the original text so that it does not use the special semantics in the regular expression.
$ Textbody = "This book is * very * difficult to find .";
$ Word = "* very *";
$ Textbody = preg_replace ("/". preg_quote ($ word )."/","". $ Word ."", $ Textbody );
// This book is output* Very *Difficult to find.
Echo htmlspecialchars ($ textbody );
?>
5. preg_grep-returned array entries in matching mode
Array preg_grep (string $ pattern, array $ input [, int $ flags = 0])
Returns an array composed of elements that match pattern in the input of the given array.
Pattern:
The pattern to be searched, in the string format.
Input:
Input array.
Flags:
If it is set to PREG_GREP_INVERT, this function returns an array consisting of elements that do not match the specified pattern in the input array.
Return value:
Returns the array indexed with the key in input.
Example:
The code is as follows:
$ Array = array ("abc", "dd", "123", "123.22", "word123", "33.2", "0.22 ");
// Returns all elements that contain floating point numbers.
// Output: Array ([3] => 123.22 [5] => 33.2 [6] => 0.22)
$ Fl_array = preg_grep ("/^ (\ d + )? \. \ D + $/", $ array );
Print_r ($ fl_array );
// Returns all elements that contain floating point numbers.
// Output: Array ([0] => abc [1] => dd [2] => 123 [4] => word123)
$ Fl_array = preg_grep ("/^ (\ d + )? \. \ D + $/", $ array, PREG_GREP_INVERT );
Print_r ($ fl_array );
?>
6. preg_replace-execute a regular expression to search and replace
Mixed preg_replace (mixed $ pattern, mixed $ replacement, mixed $ subject [, int $ limit =-1 [, int & $ count])
Search for the part in the subject that matches pattern and replace it with replacement.
Pattern:
The pattern to be searched. It can be a string or a string array. You can use some PCRE modifiers, including 'e' (PREG_REPLACE_EVAL), which can be specified for this function.
Replacement:
String or string array to be replaced. If this parameter is a string and pattern is an array, all modes use this string for replacement. If both pattern and replacement are arrays, each pattern is replaced with the corresponding elements in replacement. If replacement contains fewer elements than pattern, the extra pattern is replaced with a null string. Replacement can contain backward reference \ or (php 4.0.4 or above) $ n, which is preferred in syntax. Each such reference replaces the text captured by the nth capturing sub-group that is matched. N can be 0-99, and \ and $0 represent the complete pattern matching text. The serial number counting method of the captured sub-group is as follows: left parentheses of the captured sub-group start from left to right and start from 1. To use a backslash in replacement, you must use four, after the regular expression engine is used, it is considered as a backslash of the original article ).
When it works in the replacement mode and the back reference is followed by another number (for example, adding an original number after a matching mode ), you cannot use a syntax like \ 1 to describe backward references. For example, \ 11 will make preg_replace () unable to understand that what you want is a \ 1 back-to-reference followed by an original article 1, or a \ 11 back-to-reference followed by nothing. In this case, the solution is $ {1} 1.
This creates an independent $1 back reference and an independent original 1. When the e modifier is used, this function will escape some characters (I .e., ', ", \, and NULL) and then carry out backward reference replacement. After completing these steps, make sure that there are no syntax errors caused by single or double quotation marks (for example, 'strlen (\ '$1 \') after the back-to-reference resolution is complete \') + strlen ("$2 ")'). Make sure the PHP string syntax is followed and the eval syntax is followed. Because after replacement,
The engine evaluates the result string as the php code using the eval method and uses the return value as the final string to be replaced.
Subject:
String or string array to be searched and replaced. If the subject is an array, it is searched and replaced by each element of the subject, and the returned value is also an array.
Limit:
The maximum number of times each mode is replaced on each subject. The default value is-1 (unlimited ).
Count:
If specified, it will be filled with the number of replacement completed.
Return value:
If the subject is an array, preg_replace () returns an array, and otherwise returns a string. If the match is found, the replaced subject is returned. Otherwise, the unchanged subject is returned. If an error occurs, NULL is returned.
Example:
Use backward reference to keep up with the original value:
The code is as follows:
$ String = '0000l 15,200 3 ';
/*
* \ W + characters repeated once or multiple times
* \ D + number repeated once or multiple times
* I case-insensitive
*/
$ Pattern = '/(\ w +) (\ d +), (\ d +)/I ';
/*
* $0 complete pattern matching text
* $ {1} 1 the pattern in the first parentheses matches the text and adds 1 to the end
* \ 3 pattern matching text in the third parentheses
*/
$ Replacement = '$0:
$ {1} 1, \ 3 ';
Echo preg_replace ($ pattern, $ replacement, $ string );
?>
Use an index-based array in preg_replace:
The code is as follows:
$ String = 'The quick brown fox jumped over The lazy dog .';
$ Patterns = array ();
$ Patterns [0] = '/quick /';
$ Patterns [1] = '/brown /';
$ Patterns [2] = '/fox /';
$ Replacements = array ();
$ Replacements [2] = 'bear ';
$ Replacements [1] = 'black ';
$ Replacements [0] = 'slow ';
// Output: The bear black slow jumped over the lazy dog.
Echo preg_replace ($ patterns, $ replacements, $ string );
// Sort the mode and replaced content by key to get the expected result.
Ksort ($ patterns );
Ksort ($ replacements );
// Output: The slow black bear jumped over the lazy dog.
Echo preg_replace ($ patterns, $ replacements, $ string );
Replace some values:
The code is as follows:
$ Patterns = array ('/(19 | 20) (\ d {2})-(\ d {1, 2})-(\ d {1, 2 })/',
'/^ \ S * {(\ w +)} \ s * = /');
$ Replace = array ('\ 3/\ 4/\ 1 \ 2',' $ \ 1 = ');
Echo preg_replace ($ patterns, $ replace, '{startDate} = ');
?>
Use the modifier 'e ':
The code is as follows:
$ Html_body ="
Hello
";
// Output:
Hello
Echo htmlspecialchars (preg_replace ("/(<\/?) (\ W +) ([^>] *>)/e ",
"'\ 1'. strtoupper (' \ 2'). '\ 3 '",
$ Html_body ));
?>
Strip blank characters:
The code is as follows:
$ Str = 'foo O ';
$ Str = preg_replace ('/\ s +/', '', $ str );
// It will be changed to 'foo O'
Echo $ str;
?>
Use the count parameter:
The code is as follows:
$ Count = 0;
Echo preg_replace (array ('/\ d/', '/\ s/'), '*', 'XP 4 to',-1, $ count );
// Equivalent to echo preg_replace ('/\ d | \ s/', '', 'XP 4 to',-1, $ count );
Echo $ count; // 3
?>
7. preg_replace_callback-execute a regular expression search and use a callback to replace
Mixed preg_replace_callback (mixed $ pattern, callable $ callback, mixed $ subject [, int $ limit =-1 [, int & $ count])
In addition to specifying a callback to replacement for string replacement, this function is equivalent to preg_replace ().
Pattern:
The pattern to be searched, which can be a string or a string array.
Callback:
A callback function is called every time it needs to be replaced. during the call, the parameters obtained by the function are the matching results from the subject. The callback function returns the string to be replaced.
You may often need the callback function instead of the preg_replace_callback () function. In this case, you can use an anonymous function to define an anonymous function as the callback for the preg_replace_callback () call. In this way, you can keep all call information in the same location and do not pollute the function namespace because of a callback function name that is not used anywhere else.
Subject:
Search for the target string or string array to be replaced.
Limit:
The maximum number of times each mode can be used to replace each subject string. The default value is-1 (unlimited ).
Count:
If specified, this variable will be filled with the number of replace executions.
Example:
Preg_replace_callback () and create_function ():
The code is as follows:
// Increase the year in the text by one year.
$ Text = "maid day is 04/01/2002 \ n ";
$ Text. = "Last christmas was 12/24/2001 \ n ";
// Callback function
Function next_year ($ matches)
{
// Generally: $ matches [0] indicates a complete match.
// $ Matches [1] is the first matching capture sub-group
// And so on
Return $ matches [1]. ($ matches [2] + 1 );
}
/**
* The output is as follows:
* When L fools day is 04/01/2003
* Last christmas was 12/24/2002
*/
Echo preg_replace_callback (
"| (\ D {2}/\ d {2}/) (\ d {4}) | ",
"Next_year ",
$ Text );
// Use create_function
Echo preg_replace_callback (
"| (\ D {2}/\ d {2}/) (\ d {4}) | ",
Create_function (
'$ Matches ',
'Return $ matches [1]. ($ matches [2] + 1 );'
),
$ Text );
?>