PHP preg_match() Function
The PHP preg_match() function is a built-in function that is used to perform a regular expression match.
Syntax
The syntax of the preg_match() function is:
preg_match($pattern, $string, $matches);
Where:
- $pattern is the regular expression pattern to search for.
- $string is the string to search in.
- $matches is an optional parameter that holds the matches found.
Example
Here's an example that demonstrates how to use preg_match() function in PHP:
<?php
$string = "Hello World!";
$pattern = "/World/";
if (preg_match($pattern, $string, $matches)) {
echo "Match found!\n";
print_r($matches);
} else {
echo "Match not found.";
}
?>
Output
The output of the above example will be:
Match found!
Array
(
[0] => World
)
Explanation
In this example, we first define the string "Hello World!" and the pattern "/World/". The preg_match() function then searches for the pattern in the string and returns true if it's found, or false otherwise. In this case, the pattern is found, so the function returns true, and we use the print_r() function to display the matches found.
Use
The preg_match() function is used to search for a regular expression pattern in a string. It can be used to validate user input, search for specific patterns in a large block of text, or perform more complex string manipulation.
Important Points
- The preg_match() function is case sensitive.
- If the pattern contains a backslash () character, it must be escaped with another backslash () character.
- The optional $matches parameter returns an array of all the matches found.
Summary
- The PHP preg_match() function is used to perform a regular expression match.
- Its syntax is preg_match($pattern, $string, $matches);
- It returns true if the pattern is found in the string, or false otherwise.
- The optional $matches parameter holds the matches found.