Skip to main content

PHP RegEx Functions

PHP comes with built-in functions for working with regular expressions. These are the ones you are most likely to use:

  • preg_filter() - Returns a string or an array with pattern matches replaced, but only if matches were found
  • preg_grep() - Returns an array consisting only of elements from the input array which matched the pattern
  • preg_last_error() - Returns an error code indicating the reason that the most recent regular expression call failed
  • preg_last_error_msg() - Returns the error message indicating the reason that the most recent regular expression call failed
  • preg_match() - Searches a string and stops at the first match of a pattern
  • preg_match_all() - Searches a string for every match of a pattern
  • preg_quote() - Quotes (escapes) special characters in a string for use as a regular expression pattern
  • preg_replace() - Returns a string where matches of a pattern (or an array of patterns) are replaced with a substring (or an array of substrings) in a given string
  • preg_replace_callback() - Given an expression and a callback, returns a string where all matches of the expression are replaced with the substring returned by the callback
  • preg_replace_callback_array() - Given an array of expressions and callbacks, returns a string where all matches of each expression are replaced with the substring returned by the callback
  • preg_split() - Splits a string into an array, cutting it wherever a regular expression matches