What is preg_match() in PHP?

Overview

The preg_match() function is inbuilt in PHP. This function checks input against a described pattern. It can store the input that matches the pattern as well. This function does a regular expression match.

Syntax

The syntax of the preg_match() function is shown below:

<?php
//Syntax
preg_match(
$pattern,//A string,
$subject,//A string
$matches,//An array
$flags, //int default= 0,
$offset //int default= 0,
)
?>

Parameters

From the syntax above, it is clear that preg_match() has the following parameters:

  • pattern: The pattern parameter is simply the regular string expression that contains what is to be searched for. It is required.

  • subject: This indicates the input string which is to be searched and matched with what is in the pattern. Also a required parameter.

  • match : As the the subject is searched to see if it can be found in the pattern, preg_match will record the results of the search in an array which is provided as the third parameter. when the full pattern is matched it is saved as $match[0], if the pattern has substrings in parenthesis, the first substring to be matched with the subject will be $match[1] and so on.

  • flags: The flags of this function are:

    1. PREG_OFFSET_CAPTURE: Enabling this option simply entails, that each match, rather being a string will be an array of its own, with the first element being a substring that contains the match and the second element is the position of the first character of the substring in the input.

    2. PREG_UNMATCHED_AS_NULL - This will cause unmatched subpatterns to be returned as NULL rather than as empty strings.

And these flag/options are not required.

  • offset: This is the last parameter of this function and can be omitted as it defaults to zero. It simply tells what position in bytes on the subject the search should begin. The default zero values will mean it will start from beginning.

Code 1

This code snippet gives simple example usage of the function.

<?php
//subject
$subject = "byte sized interactive shots";
$pattern = '/ interactive shots/';
preg_match($pattern, $subject, $matches1);
preg_match($pattern, $subject, $matches2, PREG_OFFSET_CAPTURE,3);
print_r($matches1);
echo "\n=========================\n";
print_r($matches2);
?>

I hope you saw the difference between the first output from line 7 and the second output from line 9 of the code above. The second output is displayed as an array of the array due to the PREG_OFFSET_CAPTURE flag.

Code 2

<?php
preg_match('/(tic)(tac)(toe)/', 'tictactoe', $matches);
print_r($matches);
?>

In the code above, the values are displayed from the $match array, with the first item being the full-length search result as is indicated by the actions of the match parameter.

This function comes in handy when you are confirming user input on register or login.

Free Resources