POSIX-style and Perl-compatible the main functions of the two regular expressions are analogy (Preg_match, preg_replace, Ereg, ereg_replace) _php techniques

Source: Internet
Author: User
Tags chr ereg html to text modifier posix
First look at the two main functions of the POSIX-style regular expression:

Ereg function: (Regular expression match)

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 (). (General words or use Preg_match (), better le ~ ~)

Finds substrings in string that match the given regular expression pattern in a case-sensitive manner. If you find a substring that matches the child pattern within the parentheses in patterns and the function call gives the third argument regs, the match is saved in the regs array. $regs [1] contains the substring of the first opening parenthesis, $regs [2] contains the second substring, and so on. $regs [0] contains the entire matching string.

Return value: Returns the length of the matched string if a match is found in string, or FALSE if no match is found or an error occurs. This function returns 1 if there is no pass in the optional parameter regs or if the matched string length is 0.

Take a look at the Ereg () function Example:

The following code fragment accepts the date of the ISO format (YYYY-MM-DD) then with DD. Mm. YYYY Format display:
Copy Code code as follows:

<?php
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 a string for the part that matches the pattern and replaces it with replacement.
Returns the replaced string. (If no match is available for substitution, the original string is returned.) )
If pattern contains substrings in parentheses, replacement can contain substrings of the shape such as \\digit, which will be replaced with the parentheses within the number notation, and \\0 the entire contents of the string. You can use up to nine substrings. Parentheses can be nested, in which case the order is evaluated with the left parenthesis.
If a match is not found in 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 Code code as follows:

<?php
$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 () will interpret and apply the number as a sequence value of the character. For example:
Example when the 2,replacement parameter is an integer:
Copy Code code as follows:

<?php
/* cannot produce the desired result.
$num = 4;
$string = "This string has four words.";
$string = ereg_replace (' Four ', $num, $string);
Echo $string; /* Output: ' This string has words. ' *
/* This example works normally * *
$num = ' 4 ';
$string = "This string has four words.";
$string = ereg_replace (' Four ', $num, $string);
Echo $string; /* Output: ' This string has 4 words. '
?>

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

Tip: the Preg_replace () function uses Perl-compatible regular expression syntax, which is usually a faster alternative than ereg_replace ().
Let's look at the two main functions of Perl-compatible regular Expressions:
Preg_match function: (for regular expression matching)
Format: int Preg_match (string pattern, string subject [, array matches [, int flags]])
Function Description:
Searches the subject string for what 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 text that matches the child pattern in the first captured bracket, and so on.
Flags can be the following tags:
Preg_offset_capture
If you set this tag, 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 a matching string and the second 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 the pattern was matched. Either 0 times (no match) or 1 times, because Preg_match () stops the search after the first match. Preg_match_all () on the contrary, will search until the end of the subject. If error Preg_match () returns FALSE.
Tips: If you only want to see if a string is contained in another string, do not use Preg_match (). You can use Strpos () or strstr () instead, much faster.
Take a look at its example:
Example 1. Search for "PHP" in text:
Copy Code code as follows:

<?php
"I" after the pattern delimiter indicates a search with case-insensitive letters
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 the word "Web":
Copy Code code as follows:

<?php
\b In/* mode represents the boundary of a word, so only separate "web" words are matched,
* and will not match a part of "webbing" or "cobweb" * *
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 Code code as follows:

<?php
Get host name from URL
Preg_match ("/^" (http:\/\/)? [^\/]+)/I ",
"Http://www.php.net/index.html", $matches);
$host = $matches [2];
To get the following two segments from the host name
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 substituted, and if limit is omitted or the value is-1, all occurrences are replaced.
Replacement can contain \\n forms or reverse references (from PHP 4.0.4) $n form, preferred to use the latter. Each such reference is replaced with the text that matches the child pattern in the nth captured bracket. n can be from 0 to 99, where \\0 or $ refers to text that is matched by the entire pattern. Count the left parenthesis from left to right (starting from 1) to get the number of child modes.
A backward reference cannot be represented by a familiar \\1 symbol when the replacement pattern is followed by a number (that is, a number immediately following a matching pattern) after a reverse reference. \\11, for example, will make preg_replace () want a \\1 reverse reference followed by a number 1 or a \\11 reverse reference. In this case, the workaround is to use \${1}1. This creates an isolated, reverse reference, and the other 1 is just plain text.
Take a look at its example:
Example 1. The use of the following numbers followed by a reverse reference:
Copy Code code as follows:

<?php
$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 searched, the replaced subject is returned, otherwise the original subject is returned.
Each parameter (except the limit) of the 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 by Ksort () before calling Preg_replace ().
Example 2. To use an indexed array in Preg_replace ():
Copy Code code as follows:

<?php
$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 bear jumped over the lazy dog.
*/
?>

If the subject is a group, the search and replace is performed on each item in subject and an array is returned.
If both pattern and replacement are arrays, the preg_replace () then takes the value separately from the values to search for and replace the subject. If the value in replacement is less than in pattern, the 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. There is no point in the converse.
The/e modifier causes preg_replace () to use the replacement parameter as PHP code (after replacing the appropriate reverse reference). Tip: To make sure that replacement makes up a valid PHP code string, PHP will have a syntax resolution error in the report containing Preg_replace ().
Example 3. To replace a number of 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 =");
Print Preg_replace ($patterns, $replace, "{startdate} = 1999-5-27");
?>

This example will output:
$startDate = 5/27/1999
Example 4. Use the/e modifier:
Copy Code code as follows:

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

This causes all HTML tags in the input string to be capitalized.
Example 5. To convert HTML to text:
Copy Code code as follows:

<?php
$document should contain an HTML document.
This example removes HTML tags, javascript code
and whitespace characters. There will also be some generic
The HTML entity is converted to the appropriate text.
$search = Array ("' <script[^>]*?>.*?</script> ' si",//Remove JavaScript
"' <[\/\!] *? [^<>]*?> ' Si ',//Remove HTML tags
"' ([\ r \ n]) [\s]+ '],//remove white space 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 ...
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.