PHP Preg_match method

Source: Internet
Author: User

The Preg_match method uses regular expressions to process a string, save the resulting result in an array object, Array[0] Save the string matching the entire positive expression, array[1] Save the first string enclosed in parentheses, and so on.

Preg_match string $pattern string $subject array &$matches$flags$offset = 0]])

The following code:

<? PHP $pattern = "/abc (Li|wang) .../"; $arr Array (); $ret Preg_match ($pattern$arr); Echo "ret=$ret\ n"; Var_dump ($arr);

The results of the operation are as follows:

Ret=1Array(2) {  [0] = =  string(9) "abc Li fi"  [1] = =   String(2) "Li"}

As above, we get the match the entire expression "abc Li fi" and the parentheses "Li"; if we want to get the position of each match object in the original string, we can use Preg_offset_capture.

<? PHP $pattern = "/abc (Li|wang) .../"; $arr Array (); $ret Preg_match ($pattern$arr, preg_offset_capture); Echo "ret=$ret\ n"; Var_dump ($arr);

Run, get

Ret=1Array(2) {  [0] = =  array(2) {    [0] = =    string (9) "abc Li fi"    [1] = =    int (3)  }  [1] = =  array (2) {    [0] = =    string(2) "Li"    [1] = =    int ( 7)  }}

Thus, the element under Array[i] becomes an array object, contains 2 elements, and the second is the position of the pattern in the original string.

Of course Preg_match can also pass the offset parameter, which indicates where to start the match from the original string.

PHP Preg_match method

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.