Pattern matching with Perl style regular expressions.
This function does pattern matching on a string with Perl regular expressions. The first parameter is the pattern, followed by the string to look for matches in. The matches parameter is used to return the matches in an array. The first element of the matches array is the string that the entire pattern matches. The following elements of matches contain submatches within parentheses. If the optional flags parameter is set to PREG_OFFSET_CAPTURE, the matches will be returned as a two-dimensional array, where the second element for each match contains the offset of that match. The optional offset parameter can be used to start the matching at an offset from the beginning of the string. If the offset specified is negative, it is used as an offset from the end of the string.
<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("/[\w ]*PHP[\w ]*/", $s, $matches, PREG_OFFSET_CAPTURE)) {
print_r($matches);
} else {
print "The pattern did not match anything";
}
?>
</pre>
Array
(
[0] => Array
(
[0] => Coding PHP is fun
[1] => 44
)
)
The pattern matches the first sentence containing "PHP" in a string. The match and its offset are printed.