PHP » Strings » preg_match_all()

Syntax:
int preg_match_all(string pattern, string s [, array matches [, int flags [, int offset]]])
s
String to search in.
matches
Array where matches will be returned.
flags
Whether to return offsets.
offset
Offset to start the search at.

Pattern matching with Perl style regular expressions. Returns multiple matches.

This function works as preg_match(), but returns all matching portions of a string. To facilitate this, a dimension is added to the array with returned matches. The flags parameter has two additional possible values: PREG_PATTERN_ORDER means that the returned array will have all full pattern matches first, followed by all matches of the first submatch, and so on. PREG_SET_ORDER returns the first full pattern match and all its submatches followed by the next full pattern match and its submatches and so on.

Examples

Code:
<pre>
<?php

$s = "This is not the sentence we are looking for."
   . " Coding PHP is fun."
   . " Here is another sentence we do not care about."
   . " More about PHP";

if (preg_match_all("/[\w ]*PHP[\w ]*/", $s, $matches, PREG_OFFSET_CAPTURE)) {
   print_r($matches);
} else {
   print "The pattern did not match anything";
}

?>
</pre>
Output:
Array
(
   [0] => Array
       (
           [0] => Array
               (
                   [0] =>  Coding PHP is fun
                   [1] => 44
               )

           [1] => Array
               (
                   [0] =>  More about PHP
                   [1] => 110
               )
       )
)
Explanation:

Unlike preg_match(), preg_match_all() returns all the matches.

See Also: