PHP » Strings » preg_match()

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

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.



$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)) {
} else {
   print "The pattern did not match anything";

   [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.

See Also: