PHP preg_match() Function

❮ PHP RegExp Reference

Example

Use a regular expression to do a case-insensitive search for "w3schools" in a string:

<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo preg_match($pattern, $str);
?>
Try it Yourself »

Definition and Usage

The preg_match() function returns whether a match was found in a string.


Syntax

preg_match(pattern, input, matches, flags, offset)

Parameter Values

Parameter Description
pattern Required. Contains a regular expression indicating what to search for
input Required. The string in which the search will be performed
matches Optional. The variable used in this parameter will be populated with an array containing all of the matches that were found
flags Optional. A set of options that change how the matches array is structured:
  • PREG_OFFSET_CAPTURE - When this option is enabled, each match, instead of being a string, will be an array where the first element is a substring containing the match and the second element is the position of the first character of the substring in the input.
  • PREG_UNMATCHED_AS_NULL - When this option is enabled, unmatched subpatterns will be returned as NULL instead of as an empty string.
offset Optional. Defaults to 0. Indicates how far into the string to begin searching. The preg_match() function will not find matches that occur before the position given in this parameter

Technical Details

Return Value: Returns 1 if a match was found, 0 if no matches were found and false if an error occurred
PHP Version: 4+
Changelog: PHP 7.2 - Added the PREG_UNMATCHED_AS_NULL flag

PHP 5.3.6 - The function returns false when the offset is longer than the length of the input

PHP 5.2.2 - Named subpatterns can use the (?'name') and (? <name>) syntax in addition to the previous (?P<name>)

More Examples

Example

Use PREG_OFFSET_CAPTURE to find the position in the input string in which the matches were found:

<?php
$str = "Welcome to W3Schools";
$pattern = "/w3schools/i";
preg_match($pattern, $str, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
Try it Yourself »

❮ PHP RegExp Reference
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.