Definition and Usage
- PHP Version
- 4+
The preg_match()
function searches a string for a match using a given regular expression pattern.
Features
- Stops searching and returns
1
as soon as a matching pattern is found in the string. - Returns
0
if no matching pattern is found. - Returns
false
if an error occurs. - Commonly used to validate strings with specific patterns, such as email addresses, phone numbers, or URLs.
- Also used to search for specific patterns within strings or to extract data in a particular format from strings.
Basic Example
// Example: Check if an email address has a valid format
$email = 'codingcourses@example.com';
$pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/';
if (preg_match($pattern, $email)) {
echo 'The email address has a valid format.';
} else {
echo 'The email address does not have a valid format.';
}
// Output: 'The email address has a valid format.'
To find a specific pattern in a string using a regular expression and replace it with another string, use the preg_replace()
function.
Syntax
preg_match(
string $pattern,
string $subject,
array &$matches = null,
int $flags = 0,
int $offset = 0
): int|false
/* preg_match(
regular expression pattern,
the string to search,
array to store matching results[,
optional flags for additional settings[,
offset in the string to start searching]]
);
*/
Parameters
$pattern |
Required. The regular expression pattern to search for. |
---|---|
$subject |
Required. The string to search in. |
&$matches |
Optional. Specifies an array to store the results matching the regular expression pattern.
This array will be populated after the function call. It is passed by reference.
|
$flags |
Optional. Flags to specify additional settings.
The following flags can be used:
|
$offset |
Optional. The offset within the string where the search starts. This value should be an integer, and defaults to 0 if not specified. |
Return Values
The function stops searching and returns 1
as soon as a matching pattern is found in the string.
If no matching pattern is found, it returns 0
.
If an error occurs, it returns false
.
The preg_match_all()
function is similar, but it searches a string for all matches of a given regular expression pattern.
Changelog
Version | Description |
---|---|
7.2.0 | It is now possible to use the PREG_UNMATCHED_AS_NULL flag as a value for the $flags parameter. |
Practical Examples
Here are some useful examples of the preg_match()
function.
Extract Numbers
$text = 'The price is 500 dollars.';
$pattern = '/\d+/';
if (preg_match($pattern, $text, $matches)) {
echo 'Found number: ' . $matches[0];
} else {
echo 'No number found.';
}
// Output: 'Found number: 500'
Extract Domain from a URL
$url = 'https://www.example.com/page';
$pattern = '/https:\/\/(www\.)?([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,6})\/([a-zA-Z0-9.-\/]*)/';
if (preg_match($pattern, $url, $matches)) {
$domain = $matches[2];
echo 'Extracted domain: ' . $domain;
} else {
echo 'No domain found.';
}
// Output: 'Extracted domain: example'
Extract Phone Number
$text = 'A phone number in the string could be 123-456-7890.';
$pattern = '/\b(?:\d{2,3}[-.])?\d{3,4}[-.]\d{4}\b/';
if (preg_match($pattern, $text, $matches)) {
$phoneNumber = $matches[0];
echo 'Extracted phone number: ' . $phoneNumber;
} else {
echo 'No phone number found.';
}
// Output: 'Extracted phone number: 123-456-7890'
Things to Keep in Mind
Make sure the regular expression is valid. Using an invalid regular expression may lead to unexpected results.
By default, the preg_match()
function is case-sensitive.
If you want to perform a case-insensitive match, add the /i
flag to your regular expression.
$text = 'Hello, World!';
$pattern = '/hello/i';
if (preg_match($pattern, $text, $matches)) {
echo 'Found a match regardless of case: ' . $matches[0];
} else {
echo 'No matching string found.';
}
// Output: 'Found a match regardless of case: Hello'
Additional Explanation
The strpos()
function searches a string for the first occurrence of a specified substring and returns its index.
If the substring is not found, it returns false
.
$str = 'Hello, World!';
$substring = 'Hello';
$pos = strpos($str, $substring);
if ($pos === false) {
echo 'The string does not contain "Hello".';
} else {
echo 'The string contains "Hello".';
}
// Output: 'The string contains "Hello".'
References
See also
- PHP preg_replace() Function – Replace Text Using Regular Expressions
- PHP strpos() Function – Find First Substring Index
- PHP mb_strpos() Function – Multibyte-Safe Alternative to strpos()
- PHP stripos() Function – Find First Substring Index (Case-Insensitive)
- PHP mb_stripos() Function – Multibyte-Safe Alternative to stripos()
- PHP str_contains() Function – Check if a String Contains a Substring (Case-Sensitive)