PHP Regular expression matching preg_match and Preg_match_all functions

Source: Internet
Author: User
Tags php regular expression

--http://www.5idev.com/p-php_preg_match.shtml

The application of regular expressions in PHP

In PHP applications, regular expressions are mainly used to:

    • Regular match: matches the corresponding content according to the regular expression
    • Regular substitution: matches content according to regular expression and replaces
    • Regular segmentation: Splitting strings based on regular expressions

There are two types of regular expression functions in PHP, one is Perl-compatible regular expression functions, and the other is POSIX extended regular expression functions. There is little difference between the two, and it is recommended to use Perl-compatible regular expression functions, so the following are examples of Perl-compatible regular expression functions.

Delimiter

The regular expression function of Perl compatibility mode, whose regular expression needs to be written in the delimiter. Any character that is not a letter, number, or backslash () can be used as a delimiter, usually we use/as a delimiter. For specific use, see the example below.

Tips

Although the regular expression function is very powerful, if you can do it with a normal string handler, try not to use regular expression functions, because regular expressions are much less efficient. For common string processing functions, see PHP string handling.

Preg_match ()

The Preg_match () function is used to match a regular expression, successfully returning 1, otherwise returning 0.

Grammar:

int Preg_match (string pattern, string subject [, array matches])
Parameter description:
Parameters Description
Pattern Regular expressions
Subject Objects that need to be matched for retrieval
Matches Optionally, an array of matching results is stored, $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

Example 1:

<?phpif (Preg_match ("/php/i", "PHP is the Web scripting language of choice.", $matches)) {    print "A match was found:" . $matches [0];} else {    print "A match is not found.";}? >

Browser output:

A match was found:php

In this example, because I modifier is used, it is not case-sensitive to match PHP in the text.

Tips

Preg_match () The match is stopped after the first match succeeds, and if you want to match all results, that is, search to the end of subject, you need to use the Preg_match_all () function.

Example 2, get the host domain name from a URL:

<?PHP//the hostname from the URL preg_match ("/^ (http:\/\/)?" ( [^\/]+)/I "," http://www.5idev.com/index.html ", $matches); $host = $matches [2];//Take the next two paragraphs from the hostname preg_match ("/[^\.\/]+\.[ ^\.\/]+$/", $host, $matches); echo" domain name: {$matches [0]} ";? >

Browser output:

The domain name is: 5idev.com
Preg_match_all ()

The Preg_match_all () function is used to perform a regular expression global match, which returns the number of times the entire pattern match succeeds (possibly 0), and returns FALSE if an error occurs.

Grammar:

Parameter description:
Parameters Description
Pattern Regular expressions
Subject Objects that need to be matched for retrieval
Matches An array that stores the matching results
Flags

Optionally, specify the order in which the matching results are placed in the matches, and the tags that are available for selection are:

  1. Preg_pattern_order: By default, the result is sorted so that $matches [0] is an array of all pattern matches, $matches [1] is an array of strings that match the sub-patterns in the first parenthesis, and so on
  2. Preg_set_order: Sorts the results so that $matches [0] is an array of the first set of matches, $matches [1] is an array of the second set of matches, and so on
  3. Preg_offset_capture: If you set this tag, the matching result for each occurrence also returns its subordinate string offset

The following example shows that the keywords (php) in all <pre></pre> tags in the text are shown in red.

<?php$str = "<pre> learning PHP is a happy thing. </pre><pre> all the phper need to work together! </pre> "; $kw =" php ";p reg_match_all ('/<pre> ([\s\s]*?) <\/pre>/', $str, $mat), for ($i =0; $i <count ($mat [0]), $i + +) {    $mat [0][$i] = $mat [1][$i];    $mat [0][$i] = str_replace ($kw, ' <span style= ' color: #ff0000 ">". $kw. ' </span> ', $mat [0][$i]);    $str = Str_replace ($mat [1][$i], $mat [0][$i], $str);} Echo $str;? >
Regular matching Chinese characters

Regular matching Chinese characters are slightly different depending on the page encoding:

    • gbk/gb2312 code: [x80-xff]+ or [xa1-xff]+
    • UTF-8 code: [x{4e00}-x{9fa5}]+/u

Example:

<?PHP$STR = "Learning php is a happy thing." ";p Reg_match_all ("/[x80-xff]+/", $str, $match)//utf-8 use://preg_match_all ("/[x{4e00}-x{9fa5}]+/u ", $str, $match); Print_r ($match);? >

Output:

Array (    [0] = = Array        (            [0] = = Learn            [1] = = = is a happy thing.        ) )

PHP Regular expression matches preg_match and Preg_match_all functions

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.