Cyberithub

How to use preg_match in PHP [Explained with examples]

Advertisements

In this article, we will see how to use preg_match in PHP. preg_match provides a powerful, efficient, and flexible way to perform pattern matching, data validation, and string manipulation, which are common requirements in web development and data processing tasks. Regular expressions, when used with preg_match, are incredibly powerful for validating formats. Common use cases include validating email addresses, phone numbers, URLs, and other user input data.

It can also be used to quickly check conditions within a string, making it a valuable tool in form validation and data processing scenarios. Here we will see 10 best examples to understand its usage in PHP.

 

Basic Syntax

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
  • $pattern: The regular expression pattern.
  • $subject: The input string.
  • $matches: An optional array that will be filled with the results of the search.
  • $flags: Optional flags to modify the search behavior.
  • $offset: An optional parameter that specifies the offset in $subject to start searching.

 

Return Value

Returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.

 

How to use preg_match in PHP [Explained with examples]

How to use preg_match in PHP [Explained with examples]

Also Read: How to Install Selenium webdriver for PHP in 9 Easy Steps

preg_match in PHP is a function used for performing regular expression matches. It's powerful for pattern matching and string analysis. It can be used to extract specific parts of a string that match a particular pattern. This is useful in parsing strings to extract data like dates, numbers, or specific keywords.

 

Example 1: Basic Matching

In this example, we are using preg_match function to search for a specific pattern within a string and then prints a message if the pattern is found. Here a string variable $str is declared and initialized with the value "Hello World!". The if statement uses the preg_match function to search within the string $str.

Since the string $str contains the word "World", the preg_match function returns 1, making the condition in the if statement true, thus showing output "Match found!". So basically, in this code we are checking if the string "Hello World!" contains the substring "World". If it does, it prints "Match found!" as shown below on output.

<!DOCTYPE html>
<html>
<body>

<?php
$str = "Hello World!";
if (preg_match("/World/", $str)) {
    echo "Match found!";
}
?>

</body>
</html>

Output

How to use preg_match in PHP [Explained with examples] 2

 

Example 2: Case-Insensitive Matching

In the below example, we are using preg_match function in PHP for case-insensitive pattern matching within a string. Here a PHP variable named $str is declared and assigned a string value "Hi, This is from CyberITHub!". preg_match is searching for "/cyberithub/i" regular expression pattern in the string $str.

The i after the closing delimiter is a modifier that makes the pattern matching case-insensitive. This means it will match "cyberithub", "Cyberithub", "CYBERITHUB", etc., regardless of the case. Since "CyberITHub" in $str matches the pattern "/cyberithub/i" (due to the case-insensitive search), the output of this PHP script will be "Match found!".

<!DOCTYPE html>
<html>
<body>

<?php
$str = "Hi, This is from CyberITHub!";
if (preg_match("/cyberithub/i", $str)) {
   echo "Match found!";
}
?>

</body>
</html>

Output

How to use preg_match in PHP [Explained with examples] 2

 

 

Example 3: Extracting Matches

In the below example, we are using preg_match for pattern matching with regular expressions. The regular expression pattern used is "/\d+/" where \d is a special character in regex that matches any digit, and the + means "one or more times". So, "\d+" matches one or more consecutive digits. $str is the string in which the function searches for the pattern. $matches is an array that will store the matches found by preg_match().

print_r() is a PHP function that outputs human-readable information about a variable, in this case, the array $matches. If the pattern is found in $str, $matches will contain the matched parts of the string. Since the pattern "/\d+/" matches one or more digits, and $str contains "2", $matches will have "2" as its element. The output will be an array containing the single element "2", which is the number found in the string $str.

<!DOCTYPE html>
<html>
<body>

<?php
$str = "I need 2 apples";
preg_match("/\d+/", $str, $matches);
print_r($matches);
?>

</body>
</html>

Output

How to use preg_match in PHP [Explained with examples] 4

 

Example 4: Matching at the Beginning

Below example illustrates how to use regular expressions in php for pattern matching at the beginning of a string. As shown below, a PHP variable $str is declared and assigned the value "Hello, This is from CyberITHub !!". Here we are using "/^Hello/" regular expression pattern for matching. The ^ symbol in the pattern is an anchor that matches the beginning of the string.

Therefore, "/^Hello/" checks if the string starts with "Hello". The if statement evaluates whether preg_match() found the pattern at the beginning of $str. If it returns 1 (indicating a match), the code inside the if block executes. Hence the echo statement outputs "String begins with Hello" to the web page.

<!DOCTYPE html>
<html>
<body>

<?php
$str = "Hello, This is from CyberITHub !!";
if (preg_match("/^Hello/", $str)) {
    echo "String begins with Hello";
}
?>

</body>
</html>

Output

How to use preg_match in PHP [Explained with examples] 5

 

Example 5: Matching at the end

In the below example, we have declared a php variable named as $str and assigned the value "End with a period". The regular expression pattern "/\.$/" used in preg_match function can be broken down in two parts i.e "\." and "$". It can be interpreted as follows:-

  • \. : The dot "." is a special character in regular expressions, typically matching any character. To match a literal dot, it is escaped with a backslash "\", turning it into "\."
  • $ : This is an anchor character that matches the end of the string.

The if statement checks whether the pattern "/\.$/" (a period at the end of the string) is found in $str. If the pattern is found, preg_match() returns 1, and the condition evaluates to true. If the condition is true (i.e., the string $str ends with a period), the echo statement inside the if block executes, printing "String ends with a period" to the web page.

<!DOCTYPE html>
<html>
<body>

<?php
$str = "End with a period.";
if (preg_match("/\.$/", $str)) {
   echo "String ends with a period";
}
?>

</body>
</html>

Output

How to use preg_match in PHP [Explained with examples] 6

 

Example 6: Matching a specific set of characters

In the below php script example, preg_match is checking whether a given string contains at least one lowercase letter or digit and outputs a message to the web page if it does. The regular expression "/[a-z0-9]/" is used to search for any lowercase alphabetic characters or digits in the string. In this specific case, since "CyberITHub" contains lowercase letters, the message "String contains a lowercase letter or digit" will be displayed on the web page.

<!DOCTYPE html>
<html>
<body>

<?php
$str = "CyberITHub";
if (preg_match("/[a-z0-9]/", $str)) {
   echo "String contains a lowercase letter or digit";
}
?>

</body>
</html>

Output

How to use preg_match in PHP [Explained with examples] 7

 

Example 7: Negating a Character Set

In the below PHP example, we are checking if the string $str contains any character that is not a lowercase letter. The regular expression "/[^a-z]/" is used for this purpose. It is important to note that the use of negate(^) character in the expression means any character that is not a lowercase letter from a to z.

In our case, since the string "ItsFossLinux.com!" contains uppercase letters, digits, and punctuation marks (characters that are not lowercase letters), the condition in the if statement is met, and the message "String contains a character that is not a lowercase letter" will be displayed on the web page.

<!DOCTYPE html>
<html>
<body>

<?php
$str = "ItsFossLinux.com!";
if (preg_match("/[^a-z]/", $str)) {
   echo "String contains a character that is not a lowercase letter";
}
?>

</body>
</html>

Output

How to use preg_match in PHP [Explained with examples] 8

 

Example 8: Matching multiple instances

You can also make use of an extended function called preg_match_all to match all occurrences of the pattern as compared to preg_match which stops after the first match. In below example, we are declaring a php variable $str and assigning the string value '123 456 789'.

Then we are using "/\d+/" regular expression in preg_match_all function to match one or more consecutive digits in $str. All the matches found are stored in array $matches. It then outputs the results using print_r(). In our case, the pattern "/\d+/" matches three groups of digits ("123", "456", and "789"), and the output will be an array containing these three matches as shown on the below output.

<!DOCTYPE html>
<html>
<body>

<?php
$str = "123 456 789";
preg_match_all("/\d+/", $str, $matches);
print_r($matches);
?>

</body>
</html>

Output

How to use preg_match in PHP [Explained with examples] 9

 

Example 9: Matching with groups

In below PHP code snippet, pattern "/Name: (\w+), Age: (\d+)/" is used to match and capture the name and age from the string $str. The matches, including the full matched string and the individual captured groups, are stored in the array $matches, which is then printed to the web page. In our case, $matches will contain the full matched string "Name: ItsFossLinux, Age: 30", followed by the captured name "ItsFossLinux" and age "30". The output of print_r($matches) will display these elements in an array format on the web page. This uses capturing groups to extract the name and age.

<!DOCTYPE html>
<html>
<body>

<?php
$str = "Name: ItsFossLinux, Age: 30";
preg_match("/Name: (\w+), Age: (\d+)/", $str, $matches);
print_r($matches);
?>

</body>
</html>

Output

How to use preg_match in PHP [Explained with examples] 10

 

Example 10: Complex Pattern (Email Validation)

In the below code snippet, we are assigning the email address that needs to be validated in $str php variable. The regular expression pattern used in below code to be validated can be broken down and interpreted as follows:-

  • ^[a-zA-Z0-9._%+-]+ : This part of the pattern matches the beginning of the email address. It includes one or more characters that can be lowercase (a-z), uppercase (A-Z), digits (0-9), dots (.), underscores (_), percent signs (%), plus signs (+), or hyphens (-).
  • @ : This symbol is a literal match for the at symbol in the email address.
  • [a-zA-Z0-9.-]+ : This matches the domain name part of the email, which can include lowercase letters, uppercase letters, digits, dots, or hyphens.
  • \. : Escaped dot (.), matches the period before the domain extension.
  • [a-zA-Z]{2,} : This matches the domain extension, which must be at least two characters long and consist of only letters.
  • $ : This asserts the end of the string, ensuring the pattern matches the entire email address. This is an example of a regex pattern for validating an email address.

The if statement checks if the email address $str matches the specified pattern. If it does, preg_match() returns 1, making the condition true. If the condition in the if statement is true (i.e., the email address is valid according to the regular expression), the echo statement prints "Valid email address" to the web page. In our case, since "admin@itsfosslinux.com" is a correctly formatted email address, the message will be displayed.

<!DOCTYPE html>
<html>
<body>

<?php
$str = "admin@itsfosslinux.com";
if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $str)) {
    echo "Valid email address";
}
?>

</body>
</html>

Output

How to use preg_match in PHP [Explained with examples] 11

Leave a Comment