Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP preg_match() Function

PHP preg_match() Function

PHP Regular Expressions (PCRE)PHP Regular Expressions (PCRE)

The preg_match function performs a regular expression match.

Syntax



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

Searches subject for a match to the regular expression given by pattern.

Parameter Description:

  • PREG_OFFSET_CAPTURE: If this flag is passed, for every occurring match the appended string offset (relative to the target string) will be returned. Note: this changes the array filled into the matches parameter, so that each element becomes an array whose element 0 is the matched string and element 1 is the offset of that matched string within the target string subject.

  • 1.

    PREG_OFFSET_CAPTURE: If this flag is passed, for every occurring match the appended string offset (relative to the target string) will be returned. Note: this changes the array filled into the matches parameter, so that each element becomes an array whose element 0 is the matched string and element 1 is the offset of that matched string within the target string subject.

    Return Value

    Returns the number of times pattern matches. Its value will be 0 (no match) or 1, because preg_match() stops searching after the first match. preg_match_all() differs from this in that it keeps searching subject until the end is reached. If an error occurs, preg_match() returns FALSE.

    Example

    Search for the text string "php":

    The execution result is as follows:

    
    
    查找到匹配的字符串 php。
    
    

    Search for the word "web"

    The execution result is as follows:

    
    
    查找到匹配的字符串。
    
    未发现匹配的字符串。
    
    

    Extract the domain name from a URL

    The execution result is as follows:

    
    
    domain name is: runoob.com
    
    

    Using named subpatterns

    \w+): (?P \d+)/ ' , $str , $matches ) ; /* The example below works on PHP 5.2.2 (PCRE 7.0) or later; however, for backward compatibility, the approach above is the recommended way. */ // preg_match('/(? \w+): (? \d+)/', $str, $matches); print_r ( $matches ) ; ?>

    The execution result is as follows:

    
    
    Array
    
    (
    
        [0] => foobar: 2008
    
        [name] => foobar
    
        [1] => foobar
    
        [digit] => 2008
    
        [2] => 2008
    
    )
    
    

    PHP Regular Expressions (PCRE)PHP Regular Expressions (PCRE)