Open In App

PHP | preg_match() Function

Improve
Improve
Like Article
Like
Save
Share
Report

This function searches string for pattern, returns true if pattern exists, otherwise returns false. Usually search starts from beginning of subject string. The optional parameter offset is used to specify the position from where to start the search.

Syntax:

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

Parameters: This function accepts five parameters as mentioned above and described below:

  • pattern: This parameter holds the pattern to search for, as a string.
  • input: This parameter holds the input string.
  • matches: If matches exists then it contains results of search. The $matches[0] will contain the text that matched full pattern, $matches[1] will contain the text that matched the first captured parenthesized subpattern, and so on.
  • flags: The flags can be following flags:
    • PREG_OFFSET_CAPTURE: If this flag is passed, for every match the append string offset will be returned.
    • PREG_UNMATCHED_AS_NULL: If this flag is passed, subpatterns which are not matched reports as NULL; otherwise they reports as empty string.
  • offset: Usually, search starts from the beginning of input string. This optional parameter offset is used to specify the place from where to start the search (in bytes).

Return value: It returns true if pattern exists, otherwise false.

Below examples illustrate the preg_match() function in PHP:

Example 1: This example accepts the PREG_OFFSET_CAPTURE flag.




<?php
  
// Declare a variable and initialize it
$geeks = 'GeeksforGeeks';
  
// Use preg_match() function to check match
preg_match('/(Geeks)(for)(Geeks)/', $geeks, $matches, PREG_OFFSET_CAPTURE);
  
// Display matches result
print_r($matches);
  
?>


Output:

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

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

    [2] => Array
        (
            [0] => for
            [1] => 5
        )

    [3] => Array
        (
            [0] => Geeks
            [1] => 8
        )

)

Example 2:




<?php
  
// Declare a variable and initialize it
$gfg = "GFG is the best Platform.";
  
// case-Insensitive search for the word "GFG"
if (preg_match("/\bGFG\b/i", $gfg, $match)) 
    echo "Matched!";
else
    echo "not matched";
      
?>


Output:

Matched!

Reference: http://php.net/manual/en/function.preg-match.php



Last Updated : 27 Feb, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads