Regular Expression Pattern Matching with the PHP preg_match() Function

09/04/2021

Contents

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.

Syntax:

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

Sample Code

<?php
  $input = "Plantpot is a web development blog";
  $pattern = "/Plantpot/";
  preg_match("$pattern", $input, $matches, PREG_OFFSET_CAPTURE);
  print_r($matches);
?>

Result

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