Regular Expression Pattern Matching with the PHP preg_match() Function



In this article, you will learn egular expression pattern matching with the PHP preg_match() function.

PHP preg_match() Function

The preg_match function searches a string for characters that match the pattern specified by the regular expression.

This function returns 1 if there is a match, 0 otherwise.

You can use this function to search and replace strings.


preg_match($pattern, $input, [$matches], [$flags], [$offset])

$pattern: The regular expression pattern you want to match.

$input: The target string to match with the regular expression.

$matches: If an array is specified, the search results will be substituted as an array.

$flags: If PREG_OFFSET_CAPTURE is specified, the position (offset) where the matched string appeared can be obtained in bytes.

$offset: Specifies where in the string to start searching, in bytes.


Sample Code

  $input = "Plantpot is a web development blog";
  $pattern = "/Plantpot/";
  preg_match("$pattern", $input, $matches, PREG_OFFSET_CAPTURE);


Array ( [0] => Array ( [0] => Plantpot [1] => 0 ) )