YouTip LogoYouTip

Php Preg_Match_All

# PHP preg_match_all() Function [![Image 3: PHP Regular Expressions (PCRE)](#)PHP Regular Expressions (PCRE)](#) The preg_match_all function is used to perform a global regular expression match. ### Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] ) Searches subject for all matches to the regular expression given in pattern and outputs them to matches in the order specified by flags. After the first match is found, the subsequent search continues from the end of the last match. Parameter Description: * $pattern: The pattern to search for, as a string. * $subject: The input string. * $matches: A multidimensional array, used as an output parameter to output all matches. The array sorting is specified by flags. * $flags: Can be used in combination with the following flags (note that PREG_PATTERN_ORDER and PREG_SET_ORDER cannot be used simultaneously): 1. PREG_PATTERN_ORDER: The results are sorted so that matches contains all matches for the complete pattern, matches contains all matches for the first subpattern, and so on. 2. PREG_SET_ORDER: The results are sorted so that matches contains an array of all matches from the first match (including subpatterns), matches contains an array of all matches from the second match (including subpatterns), and so on. 3. PREG_OFFSET_CAPTURE: If this flag is passed, each found match will include its offset relative to the target string. * offset: Normally, the search starts at the beginning of the subject string. The optional offset parameter is used to start the search at a specified position in the subject string (in bytes). ### Return Value Returns the number of full matches (which may be 0), or FALSE on error. ### Example ## Find content matching and tags: <?php$userinfo = "Name: PHP
Title: Programming Language"; preg_match_all("/(.*)/U", $userinfo, $pat_array); print_r($pat_array); ?> The execution result is as follows: Array( => PHP => Programming Language) ## Find matching HTML tags (greedy): <?php//2 is an example of a backreference. This tells pcre it must match the result of the second set of parentheses in the regex (here (+))//Two backslashes are used here because double quotes are used.$html = "bold textclick me"; preg_match_all("/(]*>)(.*?)()/", $html, $matches, PREG_SET_ORDER); foreach($matches as$val){echo"matched: " . $val . "n"; echo"part 1: " . $val . "n"; echo"part 2: " . $val . "n"; echo"part 3: " . $val . "n"; echo"part 4: " . $val . "nn"; }?> The execution result is as follows: matched: bold text part 1: part 2: b part 3: bold text part 4: matched: click me part 1: part 2: a part 3: click me part 4: [![Image 4: PHP Regular Expressions (PCRE)](#)PHP Regular Expressions (PCRE)](#)
← Php Preg_Replace_CallbackPhp Pcre β†’