What is PHP? 

Hypertext Preprocessor is a powerful tool for making interactive and dynamic web pages. It is free, efficient, and widely-used. In the web development domain, it has become a must for professionals. As it is a server side scripting language, it can manage dynamic content, session tracking, databases, and even e-commerce websites. It has a syntax similar to C language and supports a large number of major protocols. 

PHP offers several functions, which makes it easy to work with several data types and expressions. In this article, we are going to see how PHP deals with Regex patterns using preg_match. 

What is preg_match in PHP?

preg_match in PHP function is used to search the string for a pattern and return a Boolean value. The search generally starts from the initial character of the string. An optional parameter 'offset' is used to specify the position from where the search begins, that is, an alternate position from which the search can start. Thus, preg_match in the PHP function looks for a match in the string. 

An optional input parameter, 'pattern_array,' if provided, contains various sections of sub-patterns that need to be contained in the search pattern. Also, if the flag is passed as 'PREG_OFFSET_CAPTURE,' then the appended string offset will also be returned whenever a match occurs. We will see this in the examples below, but first, let us look at the syntax. 

Syntax of preg_match in PHP

The syntax of the function is:

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

The search will start from starting the input string parameter unless specified using the optional offset parameter. 

Return Value: The function returns true if the pattern matches. If not, the function may return false. preg_match in PHP can also return a non-Boolean value, if it is evaluated to false. 

Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE CoursesEnroll Now
Stand Out From Your Peers this Appraisal Season

Parameter Values and Use Case

preg_match in PHP has five parameters. All of them are defined below:

  • pattern- This parameter has the pattern that needs to be searched in the string. 
  • input- This parameter has the string that needs to be searched.
  • matches- If there is a match, this parameter contains the search result. 
  1. $matches[0] contains the text matching full pattern;
  2. $matches[1] contains text that matches with the first recognized parenthesized subpattern which goes on. 
  • flag- The flag parameter can contain either flag:
  1. PREG_UNMATCHED_AS_NULL: When this flag is passed, subpatterns that are not matched are reported as NULL, whereas others are reported empty.
  2. PREG_OFFSET_CAPTURE: When this flag is passed, the append string offset will be returned for every match. 
  • offset- As mentioned earlier, this parameter specifies the position (in bytes) from where the search needs to start. If not specified, search by default starts from the beginning. 

Use Cases of Parameters

Let us see some examples to understand the use of every parameter:

1. Using a regular expression for doing a case-insensitive search in the given string 

<!DOCTYPE html>

<html>

<body>

<?php

$string = "preg_match in PHP";

$pattern = "/php/i";

if(preg_match($pattern, $string)){

echo "Matches";

}

else{

"Not match";

}

?>

</body>

</html>

Output:

preg_match_in_PHP_1

2. Using PREG_OFFSET_CAPTURE to find the position of the string where the match was found 

<!DOCTYPE html>

<html>

<body>

<?php

$string = "preg_match in PHP";

$pattern = "/php/i";

preg_match($pattern, $string, $matches, PREG_OFFSET_CAPTURE);

print_r($matches);

?>

</body>

</html>

Output:

preg_match_in_PHP_2.

Here, 14 is the position at which the pattern is found in the main string. 

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

3. We will see how we can use the word boundary (\b) in the pattern. This expression would return true for specific words like 'web' but false for ‘webinar’ and ‘core web’ as they do not match partially. 

<!DOCTYPE html>

<html>

<body>

<?php              

if (preg_match("/\match\b/i", "preg_match in PHP")) {  

echo "A match was found. </br>";  

} else {  

echo "A match was not found. </br>";  

}  

if (preg_match("/\bweb\b/i", "preg_match() in PHP")) {  

 echo "A match was found.";  

} else {  

    echo "A match was not found.";  

}  

?>  

</body>

</html>

Output:

preg_match_in_PHP_3

4. Let us see how we can take a domain name out of the URL

<!DOCTYPE html>

<html>

<body>

<?php    

// Specify URL as input and the given pattern to identify 

preg_match('@^(?:https://)?([^/]+)@i',  

   "https://www.php.net/", $matches);  

$host = $matches[1];   

 //This returns last two segments of domain name 

preg_match('/[^.]+\.[^.]+$/', $host, $matches);  

 echo "Domain name is: {$matches[0]}\n";  

?>  

</body>

</html>

Output:

preg_match_in_PHP_4

This particular example shows the use of the 'matches' parameter. 

Note: You should not use preg_match in PHP to check only for a substring. Use strpos in PHP for that.  

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Master PHP Today!

In this preg_match in PHP tutorial, we learned everything about the preg_match function, its use, and syntax. This function can be used to match different Regex patterns to a string.

Well, that is about the preg_match in PHP. However, if you wish to take the next step and become a jack of all trades, your aim should be mastering full stack development. And if you are interested in learning more about web development and PHP, do not forget to check out Simplilearn’s full-stack web development certification.

Don’t forget to explore SkillUp- a free learning platform by Simplilearn. This platform offers 1000+ hours of self-paced learning across 30+ essential skills for career growth. The best in the industry have created the course content and can help you scale new heights in your job.