How to use regular expressions in PHP for search replacement

Source: Internet
Author: User
Tags expression engine

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:
Copy codeThe Code is as follows:
<? Php
/*
* 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 "<br/>". "\ 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 "<br/>". "\ 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 "<br/>". "\ 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 "<br/>". "\ 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:
Copy codeThe Code is as follows:
<? Php
/*
* Output: 2
*/
Echo preg_match_all ("/php/I", "In my point, PHP is the web scripting language of choice. I love php", $ matches );
Echo "<br/>". "\ 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 "<br/>". "\ 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 "<br/>". "\ 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 "<br/>". "\ 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 "<br/>". "\ 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:
Copy codeThe Code is as follows:
<? Php
/*
* 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 "<br/>". "\ 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 "<br/>". "\ 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 "<br/>". "\ 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:
Copy codeThe Code is as follows:
<? Php
// 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). "/", "<I>". $ word. "</I>", $ textbody );
// This book is <I> * very * </I> difficult to find will be output.
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:
Copy codeThe Code is as follows:
<? Php
$ 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 \ n 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, \ 0 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 what you want is a \ 1 Back Reference followed by an original article 1, or a \ 11 Post is not followed by anything. 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:
Copy codeThe Code is as follows:
<? Php
$ 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: <br/>$ {1} 1, \ 3 ';
Echo preg_replace ($ pattern, $ replacement, $ string );
?>

Use an index-based array in preg_replace:
Copy codeThe 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:
Copy codeThe Code is as follows:
<? Php
$ 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 ':
Copy codeThe Code is as follows:
<? Php
$ Html_body = "<p> <span> hello </span> </p> ";
// Output: <P> <SPAN> hello </SPAN> </P>
Echo htmlspecialchars (preg_replace ("/(<\/?) (\ W +) ([^>] *>)/e ",
"'\ 1'. strtoupper (' \ 2'). '\ 3 '",
$ Html_body ));
?>

Strip blank characters:
Copy codeThe Code is as follows:
<? Php
$ Str = 'foo o ';
$ Str = preg_replace ('/\ s +/', '', $ str );
// It will be changed to 'foo o'
Echo $ str;
?>

Use the count parameter:
Copy codeThe Code is as follows:
<? Php
$ 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 ():
Copy codeThe Code is as follows:
<? Php
// 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 );
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.