How to use regular expressions in PHP to find and replace _php tutorials

Source: Internet
Author: User
Tags expression engine
1. preg_match-performs 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 the pattern.
Pattern
The type of pattern to search for, string.
Subject:
The input string.
Matches
If the parameter matches is supplied, it will be populated as search results. $matches [0] will contain the text that the full pattern matches to, $matches [1] will contain the text to which the first capturing subgroup matches, and so on.
Flags
Flags can be set to the following tag values: Preg_offset_capture If this token is passed, a string offset (relative to the target string) is appended to each occurrence of the match. Note: This changes the array populated to the matches parameter so that each of its elements becomes a string that is matched to 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. An optional parameter, offset, is used to specify the start of a search (in bytes) from an unknown target string.
return value:
Preg_match () returns the number of occurrences of pattern. Its value will be 0 times (mismatched) or 1 times, because Preg_match () will stop the search after the first match. Preg_match_all () differs from this, and it searches subject until the end is reached. If an error occurs, Preg_match () returns FALSE.
Example:
Copy CodeThe code is as follows:
/*
* the "I" mark after the pattern delimiter it's a case insensitive search
* Will be output: 1
*/
Echo Preg_match ("/,\s* (PHP)/I", "In my point, PHP is the Web scripting language of choice.");
echo "
"." \ n ";
/*
* Will 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 ";
/*
* Will 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 ";
/*
* Will 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-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 for all matching results in subject that match the pattern given regular expression and outputs them in flag-specified order to matches. After the first match is found, the subsequence continues to search from the last matching location.
Pattern
The pattern to search for, in string form.
Subject:
The input string.
Matches
multidimensional arrays, which output all matching results as output parameters, array ordering is specified by flags.
Flags
It 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), if no sort mark is given, the assumption is set to Preg_pattern_order:
Preg_pattern_order:
Results sorted to $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 sort is $matches[0] contains all matches that were obtained for the first match (including subgroups), $matches [1] is an array that contains all matches (including subgroups) to the second match, and so on.
Preg_offset_capture:
If this token is passed, each found match is returned with an offset to its relative target string. Note that this alters each of the matching result string elements in the matches, making it a No. 0 element to match the result string, and the 1th element as the offset of the matching result string in subject.
return value:
Returns the complete number of matches (possibly 0), or False if an error occurs.
Example:
Copy CodeThe code is as follows:
/*
* 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 "
"." \ n ";
/*
* Will 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 ";
/*
* Will 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 ";
/*
* 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 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-separating strings by a regular expression
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. A limit value of 1, 0, or null means "unrestricted", and as a standard for PHP, you can use NULL to skip the setting for flags.
Flags
Flags can be any combination of the following tags (in bits or operations | combination):
Preg_split_no_empty:
If this tag is set, Preg_split () will return to the non-empty part after the separation.
Preg_split_delim_capture:
If this tag is set, the parentheses expression in the pattern used for the separation will be captured and returned.
Preg_split_offset_capture:
If this tag is set, the string offset will be appended to each occurrence of the match returned. Note: This will change each element in the returned array so that each element becomes a delimited substring of the No. 0 element, and the 1th element is an array of the offset of the substring in subject.
return value:
Returns an array of substrings that are made using the pattern boundary to separate subject.
Example:
Copy CodeThe code is as follows:
/*
* The output will be:
*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 will be:
*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 will be:
*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-escaping regular expression characters
String Preg_quote (String $str [, String $delimiter = NULL])
Preg_quote () requires the parameter str and adds a backslash to the character in each of the regular expression syntax. This is typically used when you have some run-time strings that need to be matched as regular expressions.
The 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 delimiter.
return value:
Returns the escaped string.
Example:
Copy CodeThe code is as follows:
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 was *very* difficult to find";
$word = "*very*";
$textbody = Preg_replace ("/". Preg_quote ($word). "/", " " . $word. "", $textbody);
It will be output *very*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 of input that match pattern pattern.
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 pattern.
return value:
Returns an array that is indexed using key in input.
Example:
Copy CodeThe code is as follows:
$array = Array ("ABC", "DD", "123", "123.22", "word123", "33.2", "0.22");
Returns all elements containing 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 containing 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-Perform a search and replace of a regular expression
Mixed preg_replace (mixed $pattern, mixed $replacement, mixed $subject [, int $limit =-1 [, int & $count]])
Searches for the part of the subject that matches the pattern, replacing it with replacement.
Pattern
The mode to search for. Can be a string or an array of strings. You can use some pcre modifiers, including ' E ' (preg_replace_eval), which can be specified for this function.
Replacement:
A string or array of strings to replace. If this 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 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 back reference \\n or (PHP 4.0.4 or more) $n, which is syntactically preferred. Each such reference will be matched to the text that is captured by the nth capturing subgroup to replace. n can be 0-99,\\0 and $ A to represent the complete pattern matching text. The ordinal count of the capturing subgroup is: The opening parenthesis representing the capturing subgroup is 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, it is two, then after the regular expression engine is considered a text backslash).
When working in replacement mode and the back reference is followed by a second number (for example, adding a text number immediately after a matching pattern), you cannot use syntax such as \\1 to describe the back reference. For example, \\11 will make preg_replace () do not understand what you want is a \\1 back to the reference followed by a text 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, forward-referencing, 1-independent source. When the E modifier is used, the function escapes some characters (that is, ', ', \, and NULL) and then replaces it with a back reference. When these are done, make sure that there are no single or double quotation marks due to syntax errors after parsing the back reference (e.g. ' strlen (\ ' $1\ ') +strlen ("$"). Ensure that PHP is compliant with the string syntax and that it conforms to the eval syntax. Because after the replacement is complete,
The engine evaluates the resulting string as PHP code using eval and returns the return value as a string that will be replaced by the final participant.
Subject
A string or array of strings to search for and replace. If subject is an array, the search and replace 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 (infinity).
Count
If specified, it will be populated with 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 other cases return unchanged subject. If an error occurs, NULL is returned.
Example:
Use a back reference to follow the original value:
Copy CodeThe code is as follows:
$string = ' April 15, 2003 ';
/*
*\w+ character repeats one or more times
*\d+ number repeats one or more times
*i ignoring case
*/
$pattern = '/(\w+) (\d+), (\d+)/I ';
/*
*$0 full pattern-matching text
*${1}1 the pattern in the first parenthesis matches the text and adds 1 to the back
*\\3 pattern matching text in the third parenthesis
*/
$replacement = ' $ A:
${1}1,\\3 ';
Echo preg_replace ($pattern, $replacement, $string);
?>

Use an indexed-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 ';
Will output: The bear black slow jumped over the the lazy dog.
Echo preg_replace ($patterns, $replacements, $string);
Sort patterns and replacements by key we can get the desired results.
Ksort ($patterns);
Ksort ($replacements);
Will output: The slow black bear jumped over the the lazy dog.
Echo preg_replace ($patterns, $replacements, $string);

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

Use modifier ' e ':
Copy CodeThe code is as follows:
$html _body = "

Hello

";
Will output:

Hello


Echo Htmlspecialchars (Preg_replace ("/(<\/?) (\w+) ([^>]*>)/E ",
"' \\1 '. Strtoupper (' \\2 '). ' \\3 ' ",
$html _body));
?>

Peel whitespace characters:
Copy CodeThe code is as follows:
$str = ' foo o ';
$str = preg_replace ('/\s\s+/', ' ', $str);
will be changed to ' foo o '
Echo $str;
?>

Use the parameter count:
Copy CodeThe code is as follows:
$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-performs 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, in addition to specifying a callback substitution replacement for the calculation of the replacement string, is equivalent to Preg_replace ().
Pattern
To search for a pattern, you can make a string or an array of strings.
Callback
A callback function that is called every time a replacement is required, and the arguments that are obtained from the call are the results of matching from subject. The callback function returns a string that actually participates in the substitution.
You may often need the callback function instead of just a preg_replace_callback () call to a place. In this case, you can use an anonymous function to define an anonymous function as a callback when Preg_replace_callback () is called. Doing so allows you to keep all the 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
The target string or array of strings to search for replacements.
Limit
The maximum number of replaceable times per pattern used for each subject string. The default is-1 (No limit).
Count
If specified, this variable is populated with the number of times the substitution is performed.
Example:
Preg_replace_callback () and Create_function ():
Copy CodeThe code is as follows:
Increase the year in the text by one year.
$text = "April fools day is 04/01/2002\n";
$text. = "Last Christmas is 12/24/2001\n";
callback function
function Next_year ($matches)
{
Usually: $matches [0] is a complete match
$matches [1] is the first capturing subgroup of a match
And so on
return $matches [1]. ($matches [2]+1);
}
/**
* The output will be:
*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);
?>

http://www.bkjia.com/PHPjc/327579.html www.bkjia.com true http://www.bkjia.com/PHPjc/327579.html techarticle 1. preg_match-executes a regular expression that matches an int preg_match (string $pattern, String $subject [, array lt;? PHP/* * Pattern delimiter after the "I" flag this is a case insensitive ...

  • 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.