Open In App

PHP | preg_match() Function

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:

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


Article Tags :