How to use regular expressions to find replacements in PHP _php tips

Source: Internet
Author: User
Tags anonymous mixed modifier expression engine
1. preg_match-execution of a regular expression match
int Preg_match (string $pattern, String $subject [, Array & $matches [, int $flags = 0 [, int $offset = 0]]]
Searches for a match between the subject and the regular expression given by pattern.
Pattern
The pattern to search for, string type.
Subject:
The input string.
Matches:
If a parameter matches is provided, it is populated as a search result. $matches [0] will contain the text that the full pattern matches to, $matches [1] will contain the text that the first capturing subgroup matches to, and so on.
Flags
Flags can be set to the following tag values: Preg_offset_capture If this token is passed, the string offset (relative to the target string) is appended to each occurrence of the match. Note: This changes the array that is populated to the matches parameter so that each element becomes a string that is matched by the No. 0 element, and the 1th element is the offset of the matching string in the target string subject.
Offset
Typically, the search starts at the beginning of the target string. Optional parameter offset is used to specify an unknown start search (in bytes) from the target string.
return value:
Preg_match () returns the number of matches for pattern. Its value will be 0 times (not matched) or 1 times, because Preg_match () will stop the search after the first match. Preg_match_all () is different from this, and it searches subject until it reaches the end. Returns False if an error Preg_match () occurs.
Example:
Copy Code code as follows:

<?php
/*
* "I" mark after the * mode separator It is a case-insensitive search
* Will be output: 1
*/
Echo Preg_match ("/,\s* (PHP)/I", "In Me Point, PHP is the Web scripting language of choice.");
echo "<br/>". \ n ";
/*
* Will output: Array ([0]=>, PHP [1]=>php)
*/
$matches = Array ();
Preg_match ("/,\s* (PHP)/I", "In Me Point, PHP is the Web scripting language of choice. I love php ", $matches);
Print_r ($matches);
echo "<br/>". \ n ";
/*
* Will output: Array ([0]=>array ([0]=>, PHP [1]=>11) [1]=>array ([0]=>php [1]=>13)]
*/
Preg_match ("/,\s* (PHP)/I", "In Me Point, PHP is the Web scripting language of choice. I love php ", $matches, Preg_offset_capture);
Print_r ($matches);
echo "<br/>". \ n ";
/*
* Will output: Array ([0]=>array [0]=>e php [1]=63] [1]=>array ([0]=>php [1]=>65)]
*/
Preg_match ("/[,a-z]?\s* (PHP)/I", "In Me 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-performs a global regular expression match
int Preg_match_all (string $pattern, String $subject [, Array & $matches [, int $flags = Preg_pattern_order [, int $o Ffset = 0]]]
Searches all matches in the subject that match pattern given regular expressions and outputs them to the matches in flag specified order. After the first match is found, the child sequence continues searching from the last match location.
Pattern
The pattern to search for, in string form.
Subject:
The input string.
Matches:
A multidimensional array that outputs all matches as output parameters, and array sorting is specified by flags.
Flags
Can be used in conjunction with the following tags (note that preg_pattern_order and Preg_set_order cannot be used at the same time), and if no sort tag is given, it is assumed to be set to Preg_pattern_order:
Preg_pattern_order:
Results sorted as $matches[0] saves all matches for the full pattern, $matches [1] saves all matches for the first subgroup, and so on.
Preg_set_order:
The result is sorted as $matches[0] contains all the matches (including subgroups) that were obtained for the first match, $matches [1] is an array that contains all the matches (including subgroups) that are matched to the second time, and so on.
Preg_offset_capture:
If this token is passed, each found match is returned with an increase in its relative offset to the target string. Note that this will change each matching result string element in the matches so that it becomes a No. 0 element that matches the result string, and the 1th element is the offset of the matching result string in subject.
return value:
Returns the full number of matches (possibly 0), or False if an error occurs.
Example:
Copy Code code as follows:

<?php
/*
* Will be 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 ";
/*
* Will output: Array ([0]=>, PHP [1]=>php)
*/
$matches = Array ();
Preg_match ("/[,a-z]?\s* (PHP)/I", "In Me Point, PHP is the Web scripting language of choice. I love php ", $matches);
Print_r ($matches);
echo "<br/>". \ n ";
/*
* Will output: Array ([0]=>array (0]=&GT;, PHP [1]=>e php) [1]=>array ([0]=>php [1]=>php])
*/
$matches = Array ();
Preg_match_all ("/[,a-z]?\s* (PHP)/I", "In Me Point, PHP is the Web scripting language of choice. I love php ", $matches, Preg_pattern_order);
Print_r ($matches);
echo "<br/>". \ n ";
/*
* Will output: 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 Me 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 Me 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-A regular expression to separate strings
Array Preg_split (String $pattern, string $subject [, int $limit =-1 [, int $flags = 0]])
Separates the given string by a regular expression.
Pattern
The pattern used for the search, in string form.
Subject
Input string
Limit
If specified, the maximum number of substrings that will be delimited is only limit, and the last substring returned will contain all remaining parts. The limit value of 1, 0, or null means "No Limit", and as a PHP standard, you can skip the flags setting using NULL.
Flags
Flags can be any combination of the following tags (in bits or operations | combination):
Preg_split_no_empty:
If this tag is set, the Preg_split () is entered to return the separated non-empty part.
Preg_split_delim_capture:
If this tag is set, the bracket expression in the pattern used to delimit is captured and returned.
Preg_split_offset_capture:
If this tag is set, the string offset will be appended for each occurrence of the match. Note: This will change each element in the returned array so that each element becomes a substring separated by the No. 0 element, and the 1th element is an array of the offsets of the substring in subject.
return value:
Returns an array of substrings that are separated by a pattern boundary subject.
Example:
Copy Code code as follows:

<?php
/*
* Will be output:
*array ([0] => in me point, [1] => is the Web scripting language of choice. I Love [2] =>)
*/
$matches = Array ();
Print_r (Preg_split ("/php/i", "In Me", PHP is the Web scripting language of choice.) I love php "));
echo "<br/>". \ n ";
/*
* Will be output:
*array ([0] => in me point, [1] => is the Web scripting language of choice. I love PHP)
*/
$matches = Array ();
Print_r (Preg_split ("/php/i", "In Me", PHP is the Web scripting language of choice.) I Love PHP ", 2));
echo "<br/>". \ n ";
/*
* Will be output:
*array ([0] => in me point, [1] => is the Web scripting language of choice. I Love)
*/
$matches = Array ();
Print_r (Preg_split ("/php/i", "In Me", 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 argument str and adds a backslash to the characters in each regular expression syntax. This is usually used when you have some run-time strings that need to be matched as regular expressions.
Regular expression special characters are:. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -
Str:
Input string
Delimiter
If an optional parameter delimiter is specified, it is also escaped. This is typically used to escape the delimiter used by the Pcre function. /is the most common separator.
return value:
Returns the escaped string.
Example:
Copy Code code as follows:

<?php
In this example, Preg_quote ($word) is used to maintain the original meaning of the asterisk so that it does not use special semantics in regular expressions.
$textbody = "This book are *very* difficult to find.";
$word = "*very*";
$textbody = Preg_replace ("/". Preg_quote ($word). "/", "<i>". $word. "</i>", $textbody);
This will be <i>*very*</i> difficult to find.
echo Htmlspecialchars ($textbody);
?>

5.preg_grep-Returns an array entry for the matching pattern
Array Preg_grep (string $pattern, array $input [, int $flags = 0])
Returns an array of elements in the given array input that match pattern patterns.
Pattern
The pattern to search for, in string form.
Input
The input array.
Flags
If set to Preg_grep_invert, this function returns an array of elements in the input array that do not match the given pattern patterns.
return value:
Returns an array that is indexed using the key in input.
Example:
Copy Code code 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-performs a regular expression search and replace
Mixed preg_replace (mixed $pattern, mixed $replacement, mixed $subject [, int $limit =-1 [, int & $count]])
Searches the part of the subject that matches the pattern and replaces it with replacement.
Pattern
The pattern to search for. Can be a string or an array of strings. You can use some pcre modifiers, including ' E ' (preg_replace_eval), that you can specify for this function.
Replacement:
The string or array of strings to replace. If the argument is a string and pattern is an array, then all patterns are replaced with this string. If both pattern and replacement are arrays, each pattern is replaced with the corresponding element in the replacement. If the elements in the replacement are less than the pattern, the extra pattern is replaced with an empty string. Replacement can include a \\n reference or (PHP 4.0.4 above) $n, which is preferred syntactically. Each such reference is replaced by the text that is captured by the nth capturing subgroup that is matched to. n can be 0-99,\\0 and $ representing the complete pattern-matching text. The ordinal count of a captured subgroup is: represents the left parenthesis of the capturing subgroup from left to right, starting at 1. If you want to use backslashes in replacement, you must use 4 ("\\\\"), because this is the first PHP string, after escaping, is two, after the regular expression engine is considered to be a text backslash.
When you work in Replace mode and follow the reference followed by another number (for example, after adding a text number after a matching pattern), you cannot use syntax such as \\1 to describe a back reference. For example, \\11 will make preg_replace () not understand what you want is a \\1 followed by a reference to the original 1, or a \\11 after the reference is not followed by anything. In this case the solution is to use ${1}1.
This creates a separate $1 quote, an independent version of the original. When the E modifier is used, the function escapes some characters (that is, ', ', \, and NULL) and then replaces it with a later reference. When these are done, make sure that there are no syntax errors (such as: ' Strlen (\ $1\ ') +strlen ("$") that are caused by a single or double quotation mark after parsing the reference. Make sure that you conform to the string syntax of PHP and that it conforms to the eval syntax. Because after the replacement is complete,
The engine evaluates the result string as a PHP code using the Eval method and returns the return value as the string that ultimately participates in the substitution.
Subject
A string or array of strings to search and replace. If subject is an array, the search and replace back is performed on each element of the subject, and the return value is an array.
Limit
The maximum number of times each pattern is replaced on each subject. The default is-1 (infinite).
Count
If specified, will be populated as the number of replacements completed.
return value:
If subject is an array, preg_replace () returns an array, and in other cases returns a string. If the match is found, the replaced subject is returned, and in other cases the subject is returned unchanged. Returns NULL if an error occurs.
Example:
Use a back reference to follow the value text:
Copy Code code as follows:

<?php
$string = ' April 15, 2003 ';
/*
*\w+ character repeats one or more times
*\d+ number repeats one or more times
*i Ignore case
*/
$pattern = '/(\w+) (\d+), (\d+)/I ';
/*
*$0 complete pattern-matching text
*${1}1 the pattern in the first parenthesis matches the text and adds 1 to the back
*\\3 the pattern matching text in the third parenthesis
*/
$replacement = ' $0:<br/> ${1}1,\\3 ';
Echo preg_replace ($pattern, $replacement, $string);
?>

An indexed array is used in Preg_replace ():
Copy Code code 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 ';
Will output: The bear black slow jumped over the lazy dog.
Echo preg_replace ($patterns, $replacements, $string);
Sort the patterns and replacements by key we can get the desired result.
Ksort ($patterns);
Ksort ($replacements);
Will output: The slow black bear jumped over the lazy dog.
Echo preg_replace ($patterns, $replacements, $string);

Replace some values:
Copy Code code 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} = 1999-5-27 ');
?>

Use modifier ' e ':
Copy Code code as follows:

<?php
$html _body = "<p><span>hello</span></p>";
Will output:<p><span>hello</span></p>
Echo Htmlspecialchars (Preg_replace (<\/?) (\w+) ([^>]*>)/e ",
"' \\1 '. Strtoupper (' \\2 ')." \\3 ' ",
$html _body));
?>

To peel white space characters:
Copy Code code as follows:

<?php
$str = ' foo o ';
$str = preg_replace ('/\s\s+/', ', ', $str);
will be changed to ' foo o '
Echo $str;
?>

Use parameter count:
Copy Code code as follows:

<?php
$count = 0;
echo preg_replace (Array ('/\d/', '/\s/'), ' * ', ' XP 4 to ',-1, $count);
Equivalent to the Echo preg_replace ('/\d|\s/', ', ', ' XP 4 to ',-1, $count);
Echo $count; 3
?>

7.preg_replace_callback-executes a regular expression search and replaces it with a callback
Mixed Preg_replace_callback (mixed $pattern, callable $callback, mixed $subject [, int $limit =-1 [, int & $count] ] )
The behavior of this function can be computed in addition to a callback substitution replacement for substitution strings, and other aspects equal to the preg_replace ().
Pattern
To search for a pattern, you can make a string or an array of strings.
Callback
A callback function that is invoked each time a replacement is required, and the arguments that are obtained by the call-time function are the result of matching from the subject. The callback function returns the string that really participates in the substitution.
You may often need the callback function and only for Preg_replace_callback () a local call. In this case, you can use an anonymous function to define an anonymous function as a callback when Preg_replace_callback () is invoked. This allows you to keep all call information in the same location and not pollute the function namespace because of a callback function name that is not used anywhere else.
Subject
To search for a replacement target string or array of strings.
Limit
The maximum number of substitutions per subject string for each pattern. The default is-1 (unrestricted).
Count
If specified, this variable is populated as the number of times the execution is replaced.
Example:
Preg_replace_callback () and Create_function ():
Copy Code code as follows:

<?php
Increases the year in the text by one year.
$text = "April fools day is 04/01/2002\n";
$text. = "Last Christmas was 12/24/2001\n";
callback function
function Next_year ($matches)
{
Usually: $matches [0] is the completed match
$matches [1] is the first match to capture subgroups
Analogy
return $matches [1]. ($matches [2]+1);
}
/**
* Will be output:
*april 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);
Using 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.