Syntax:int preg_match ($pattern, $input, $matches, $flags, $offset)
Parameters: This function takes five parameters as above and described below:
- pattern:this parameter contains the pattern to search as a string.
- input:this parameter contains the input string.
- matches:if matches exist, they contain the search results. $Match [0] will contain text that matches the full pattern, $match [1] will contain text that matches the first captured subpattern, and so on.
- flags: Flags can be the following flags:
- PREG_OFFSET_CAPTURE:if passed, the offset of the added row will be returned for each match.
- PREG_UNMATCHED_AS_NULL: if this flag is omitted, subpatterns that do not match are reported as NULL; otherwise they are reported as an empty string.
- offset:usually the search starts at the beginning of the input string. This optional offset parameter is used to specify where to start the search (in bytes).
Return Value:returns true if the pattern exists, otherwise - false.The following are examples to illustrate the preg_match() function in PHP:Example 1:This example accepts the PREG_OFFSET_CAPTURE flag.
// Declare a variable and initialize it
$engineer
=
’GeeksforGeeks’
;
// Use preg_match() to check for compliance
preg_match (
’/ (Geeks) (for) (Geeks) /’
,
$engineer
,
$matches
, PREG_OFFSET_CAPTURE);
// Show the result of matches
print_r (
$matches
);
?>
Exit: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:
// Declare a variable and initialize it
$gfg
=
"GFG is the best Platform."
;
// case insensitive search for the word & quot; GFG & quot;
if
(preg_match (
"/ GFG / i"
,
$gfg
,
$match
))
echo
"Matched!"
;
else
echo
" not matched "
;
?>
Exit:Matched!
Link: http://php.net/manual/ en / function.preg-match.php