Pattern Matching in PHP


PHP’s main pattern  matching function is preg_match() . This function takes the following arguments:

  • The regular expression to search for (as a string)
  • The string to search through
  • An optional array to store any matched text in.
  • An optional integer specifying any flags for the match operation. Currently only one flag is supported: PREG_OFFSET_CAPTURE . Pass this constant to get preg_match() to return the position of any match in the array as well as the text matched.
  • An optional integer offset from the start of the string (the first character has an offset of zero, the second character has an offset of 1, and so on). If specified, preg_match() starts the search from this position in the string, rather than from the first character.

preg_match() returns zero if the pattern did not match, or 1 if it did match. (preg_match() only finds the first match within the string. If you need to find all the matches in a string, use preg_match_all().