POSIX-style and compatible Perl-style analogue of the main functions of two regular expressions (Preg_match, preg_replace,_php tutorial

Source: Internet
Author: User
Tags ereg posix
Let's take a look at the two main functions of the POSIX-style regular expression:

Ereg function: (Regular expression matching)

Format: int ereg (string pattern, string string [, array &regs])
Note: the Preg_match () function that uses Perl-compatible regular expression syntax is usually a faster alternative than ereg (). (Generally speaking or using Preg_match (), better le ~ ~)

Finds substrings in a string that match the pattern of a given regular expression in a case-sensitive manner. If a substring that matches the sub-pattern in parentheses in pattern is found and the function call gives the third parameter regs, the match is stored in the regs array. $regs [1] contains a substring starting with the first opening parenthesis, $regs [2] contains the second substring, and so on. The $regs [0] contains the entire matched string.

Return value: If a match of pattern pattern is found in string, the length of the matched string is returned, and FALSE is returned if no match is found or an error occurs. If you do not pass in an optional parameter regs, or if the string length is 0, the function returns 1.

Take a look at the example of the Ereg () function:

The following code fragment accepts the ISO format date (YYYY-MM-DD) and then with DD. Mm. YYYY Format display:
Copy CodeThe code is as follows:
if (Ereg ([[0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ", $date, $regs)) {
echo "$regs [3]. $regs [2]. $regs [1]";
} else {
echo "Invalid date format: $date";
}
?>

-----------------------------------------------------------------------------------
Ereg_replace function: (Regular expression substitution)

Format: String ereg_replace (string pattern, string replacement, string string)
Function Description:
This function scans the string for the part that matches the pattern and replaces it with replacement.
Returns the replaced string. (The original string is returned if there is no match to replace.) )
If pattern contains substrings within parentheses, the replacement can contain substrings of the form \\digit, which are replaced with substrings within the parentheses of the number representation, and \\0 contain the entire contents of the string. A maximum of nine substrings can be used. Parentheses can be nested, in which case a left parenthesis is used to calculate the order.
If no match is found in the string, the string is returned as-is.
Let's take a look at this function example:
1, the following code fragment outputs "This is a Test" three times:
Copy CodeThe code is as follows:
$string = "This is a test";
Echo Str_replace ("is", "was", $string);
Echo ereg_replace ("() is", "\\1was", $string);
Echo ereg_replace ("() is)", "\\2was", $string);
?>

One thing to note is that if you use an integer value in the replacement parameter, you may not get the desired result. This is because ereg_replace () interprets the number as a sequence value of the character and applies it. For example:
An example of an integer when the 2,replacement parameter is:
Copy CodeThe code is as follows:
/* Cannot produce desired results */
$num = 4;
$string = "This string had four words.";
$string = ereg_replace (' Four ', $num, $string);
Echo $string; /* Output: ' This string has words. ' */
/* This example works fine */
$num = ' 4 ';
$string = "This string had four words.";
$string = ereg_replace (' Four ', $num, $string);
Echo $string; /* Output: ' This string has 4 words. ' */
?>

3. Replace the URL with a hyperlink:
Copy CodeThe code is as follows: $text = Ereg_replace ("[[: alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
"\\0", $text);

Tip: the Preg_replace () function uses Perl-compatible regular expression syntax, which is usually a faster alternative than ereg_replace ().
Take a look at the two main functions of a Perl-compatible regular expression:
Preg_match function: (Regular expression matching)
Format: int Preg_match (string pattern, string subject [, array matches [, int flags]])
Function Description:
Searches the subject string for content that matches the regular expression given by pattern.
If matches is provided, it is populated with the results of the search. $matches [0] will contain text that matches the entire pattern, $matches [1] will contain the text that matches the sub-pattern in the first captured parenthesis, and so on.
Flags can be the following tags:
Preg_offset_capture
If this tag is set, the matching result for each occurrence also returns its subordinate string offset. Note that this changes the value of the returned array so that each cell is also an array, where the first item is the matching string, and the second item is its offset. This tag is available from PHP 4.3.0.
The flags parameter is available from PHP 4.3.0.
Preg_match () returns the number of times that pattern matches. Either 0 times (no match) or 1 times, because Preg_match () stops searching after the first match. Preg_match_all () Instead, it searches until the end of subject. If error Preg_match () returns FALSE.
Tips: If you just want to see if a string is contained in another string, do not use Preg_match (). Can be replaced with strpos () or strstr (), much faster.
Let's take a look at its example:
Example 1. Search for "PHP" in the text:
Copy CodeThe code is as follows:
The "I" after the pattern delimiter indicates a search with a case-insensitive letter
if (Preg_match ("/php/i", "PHP is the Web scripting language of choice.")) {
Print "A match was found.";
} else {
Print "A match is not found.";
}
?>

Example 2. Search for the word "Web":
Copy CodeThe code is as follows:
The \b In/* mode represents the boundaries of the word, so only separate "web" words will be matched,
* Does not match part of "webbing" or "cobweb", for example */
if (Preg_match ("/\bweb\b/i", "PHP is the Web scripting language of choice.")) {
Print "A match was found.";
} else {
Print "A match is not found.";
}
if (Preg_match ("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
Print "A match was found.";
} else {
Print "A match is not found.";
}
?>

Example 3. Remove the domain name from the URL:
Copy CodeThe code is as follows:
Get host name from URL
Preg_match ("/^ (http:\/\/)?" ( [^\/]+)/I ",
"Http://www.php.net/index.html", $matches);
$host = $matches [2];
Get the next two paragraphs from the hostname
Preg_match ("/[^\.\/]+\.[ ^\.\/]+$/", $host, $matches);
echo "Domain name is: {$matches [0]}\n";
?>

This example will output:
Domain name Is:php.net
-----------------------------------------------------------------------------------
Preg_replace function: (performs search and replace of regular expressions)
Format: Mixed preg_replace (mixed pattern, mixed replacement, mixed subject [, int limit])
Function Description:
Searches the subject for a match in pattern mode and replaces it with replacement. If limit is specified, only the limit match is replaced, and if the limit is omitted or the value is-1, all occurrences are replaced.
Replacement can contain a \\n form or a reverse reference (since PHP 4.0.4) $n form, preferably using the latter. Each of these references will be replaced with text that matches the sub-pattern in the nth captured parentheses. n can be from 0 to 99, where \\0 or $ refers to text that is matched by the entire pattern. The left parenthesis is counted from left to right (starting at 1) to get the number of sub-patterns.
When the replacement pattern is followed by a number immediately after a reverse reference (that is, a number immediately following a matching pattern), you cannot use a familiar \\1 symbol to represent a reverse reference. \\11, for example, will make preg_replace () unclear if it wants a \\1 inverse reference followed by a number 1 or a \\11 inverse reference. The workaround in this example is to use \${1}1. This creates an isolated reverse reference, and makes the other 1 simple text.
Take a look at its example:
Example 1. The inverse reference is followed by the use of the number:
Copy CodeThe code is as follows:
$string = "April 15, 2003";
$pattern = "/(\w+) (\d+), (\d+)/I";
$replacement = "\${1}1,\$3";
Print Preg_replace ($pattern, $replacement, $string);
/* Output
======
april1,2003
*/
?>

If a match is found, the replaced subject is returned, otherwise the original unchanged subject is returned.
Each parameter (except limit) of Preg_replace () can be an array. If both pattern and replacement are arrays, they are processed in the order in which their key names appear in the array. This is not necessarily the same as the numeric order of the index. If you use an index to identify which pattern will be replaced by which replacement, you should sort the array with Ksort () before calling Preg_replace ().
Example 2. To use an indexed array in Preg_replace ():
Copy CodeThe code is as follows:
$string = "The quick brown fox jumped over the lazy dog.";
$patterns [0] = "/quick/";
$patterns [1] = "/brown/";
$patterns [2] = "/fox/";
$replacements [2] = "Bear";
$replacements [1] = "BLACK";
$replacements [0] = "slow";
Print Preg_replace ($patterns, $replacements, $string);
/* Output
======
The bear black slow jumped over the lazy dog.
*/
/* by ksorting patterns and replacements,
We should get what we wanted. */
Ksort ($patterns);
Ksort ($replacements);
Print Preg_replace ($patterns, $replacements, $string);
/* Output
======
The slow black jumped over the lazy dog.
*/
?>

If subject is an array, the search and replace is performed on each item in the subject, and a collection is returned.
If both pattern and replacement are arrays, then preg_replace () extracts the values from each to search for and replace the subject. If the value in replacement is less than in pattern, an empty string is used as the remaining replacement value. If pattern is an array and replacement is a string, this string is used as the replacement value for each value in pattern. In turn, it doesn't make sense.
The/E modifier causes preg_replace () to treat the replacement parameter as PHP code (after the appropriate reverse reference is replaced). Tip: To make sure that replacement constitutes a valid PHP code string, PHP will have a parsing error in the report line that contains Preg_replace ().
Example 3. Replace several 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 =");
Print Preg_replace ($patterns, $replace, "{startdate} = 1999-5-27");
?>

This example will output:
$startDate = 5/27/1999
Example 4. Use the/E modifier:
Copy CodeThe code is as follows:
Preg_replace ("/(<\/?) (\w+) ([^>]*>)/E ",
"' \\1 '. Strtoupper (' \\2 '). ' \\3 ' ",
$html _body);
?>

This will make all HTML tags in the input string uppercase.
Example 5. To convert HTML into text:
Copy CodeThe code is as follows:
$document should contain an HTML document.
This example removes the HTML tag, and the JavaScript code
and white space characters. will also be some of the common
The HTML entity is converted to the appropriate text.
$search = Array ("' Si",//Remove JavaScript
"' <[\/\!] *? [^<>]*?> ' Si ',//Remove HTML tags
"' ([\ r \ n]) [\s]+ '",//Remove whitespace characters
"' & (quot| #34); ' I ",//Replace HTML entity
"' & (amp| #38); ' I ",
"' & (lt| #60); ' I ",
"' & (gt| #62); ' I ",
"' & (nbsp| #160); ' I ",
"' & (iexcl| #161); ' I ",
"' & (cent| #162); ' I ",
"' & (pound| #163); ' I ",
"' & (copy| #169); ' I ",
"' (\d+); ' E "); Run as PHP code
$replace = Array ("",
"",
"\\1",
"\"",
"&",
"<",
">",
" ",
Chr (161),
Chr (162),
Chr (163),
Chr (169),
"Chr (\\1)");
$text = Preg_replace ($search, $replace, $document);
?>

The End ...

http://www.bkjia.com/PHPjc/322544.html www.bkjia.com true http://www.bkjia.com/PHPjc/322544.html techarticle first, consider the two main functions of the POSIX-style regular expression: The Ereg function: (regular expression matching) format: int ereg (string pattern, string string [, Array lt;?). php if ( ...).

  • Related Article

    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.