Regular Expression functions of PHP and php

Source: Internet
Author: User

Regular Expression functions of PHP and php
Previous

Regular Expressions cannot be used independently. They are only a rule pattern used to define strings and must be applied in the corresponding regular expression functions, to match, search, replace, and split strings. This section describes the basic syntax of regular expressions.

 

Matching and searching

[Preg_match ()]

The preg_match () function is used to execute a regular expression match and search for a match between the subject and the regular expression given by pattern. 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 the error preg_match () occurs, FALSE is returned.

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

Pattern indicates the pattern to be searched, string type

Subject indicates the input string

If the matches parameter is provided, it is filled with search results. $ Matches [0] will contain the text matching the full mode, $ matches [1] will contain the text matching the first capture sub-group, and so on

Flags can be set to the following labels: 1. PREG_OFFSET_CAPTURE. If this flag is passed, a string offset (relative to the target string) will be appended to each returned matching result ). 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; 2. 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)

<? Php // obtain the host name preg_match ('@ ^ (? : Http ://)? ([^/] +) @ I ', "http://www.php.net/index.html", $ matches); $ host = $ matches [1]; // obtain the last two parts of the Host Name preg_match ('/[^.] + \. [^.] + $/', $ host, $ matches); // domain name is: php. netecho "domain name is: {$ matches [0]} \ n";?>
<?php $pattern = '/www\.[^\.\/]+\.com/i';$subject = 'www.baidu.com,www.qq.com,www.cnblogs.com';preg_match($pattern,$subject,$matches);/*array (size=1)  0 => string 'www.baidu.com' (length=13) */var_dump($matches);?>

[Preg_match_all ()]

Preg_match_all () is similar to preg_match (). The difference is that preg_match () will stop searching after the first match, and the preg_match_all () function will always search for the end of the specified string, all matching results can be obtained.

int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )
<?php $pattern = '/www\.[^\.\/]+\.com/i';$subject = 'www.baidu.com,www.qq.com,www.cnblogs.com';preg_match_all($pattern,$subject,$matches);/*array (size=1)  0 =>     array (size=3)      0 => string 'www.baidu.com' (length=13)      1 => string 'www.qq.com' (length=10)      2 => string 'www.cnblogs.com' (length=15) */var_dump($matches);?>

[Preg_grep ()]

Preg_grep () returns an array consisting of elements that match pattern in the input of the given array.

array preg_grep ( string $pattern , array $input [, int $flags = 0 ] )

If flags 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.

<?php $pattern = '/www\.[^\.\/]+\.com/i';$subject = ['baidu.com','www.qq.com','www.cnblogs.com'];var_dump (preg_grep($pattern,$subject));/*array (size=2)  1 => string 'www.qq.com' (length=10)  2 => string 'www.cnblogs.com' (length=15) */?>

 

Replace

[Preg_replace ()]

Preg_replace (): execute a regular expression to search for replacement. Search for the part where the subject matches pattern and replace it with replacement.

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

Replacement indicates the replacement string or string array. 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.

<?php$string = 'April 15, 2016';$pattern = '/(\w+) (\d+), (\d+)/i';$replacement = '${1}1,$3';//April1,2016echo preg_replace($pattern, $replacement, $string);?>
<?php$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';//The bear black slow jumped over the lazy dog.echo preg_replace($patterns, $replacements, $string);?>

[Preg_replace_callback ()]

Preg_replace_callback () executes a regular expression search and uses a callback to replace

mixed preg_replace_callback ( mixed $pattern , callable $callback , mixed $subject [, int $limit = -1 [, int &$count ]] )
<? 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 next_year ($ matches) {// usually: $ matches [0] indicates a complete match. // $ matches [1] indicates the first matching to capture sub-groups. // return $ matches [1]. ($ matches [2] + 1 );} /* optional 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);?>

[Preg_filter ()]

Preg_filter () executes a regular expression to search and replace. It is equivalent to preg_replace (). Besides, it only returns (possibly converted) matching results with the target.

mixed preg_filter ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
<?php$subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4'); $pattern = array('/\d/', '/[a-z]/', '/[1a]/'); $replace = array('A:$0', 'B:$0', 'C:$0'); /*Array(    [0] => A:C:1    [1] => B:C:a    [2] => A:2    [3] => B:b    [4] => A:3    [7] => A:4) */print_r(preg_filter($pattern, $replace, $subject)); /*Array(    [0] => A:C:1    [1] => B:C:a    [2] => A:2    [3] => B:b    [4] => A:3    [5] => A    [6] => B    [7] => A:4) */print_r(preg_replace($pattern, $replace, $subject)); ?>

 

Split

[Preg_split ()]

Preg_split () separates strings using a regular expression

array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )

If limit is specified, only the limit substrings can be separated by a limit. The last substring returned contains all the remaining parts. If the limit value is-or null, it indicates "unlimited". You can use null to skip flags settings.

Flags can be a combination of any of the following tags (bitwise OR operation | combination): PREG_SPLIT_NO_EMPTY -- if this tag is set, preg_split () will return the non-empty parts after the separation; 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, the string offset will be appended to each 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 consisting of the offset of the substring in the subject.

<? Php // use commas (,) or spaces (including "", \ r, \ t, \ n, \ f) to separate the phrase $ keywords = preg_split ("/[\ s,] +/"," hypertext language, programming ");/* Array ([0] => hypertext [1] => language [2] => programming) */print_r ($ keywords);?>

 

Escape

[Preg_quote ()]

Preg_quote () Escape Regular Expression characters

string preg_quote ( string $str [, string $delimiter = NULL ] )

Special characters in a regular expression include:. \ + *? [^] $ () {}=! <> | :-

<? Php $ keywords = '$40 for a g3/100'; $ keywords = preg_quote ($ keywords,'/'); echo $ keywords; // returns \ $40 for a g3 \/400?>

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.