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.
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 will contain the text that matched full pattern, $matches 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.
Array (  => Array (  => GeeksforGeeks  => 0 )  => Array (  => Geeks  => 0 )  => Array (  => for  => 5 )  => Array (  => Geeks  => 8 ) )
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.