Understanding PHP preg_match() Function with Detailed Examples
This article explains the PHP preg_match() function, its parameters, return values, and optional flags, and provides four practical code examples demonstrating simple pattern matching, word‑boundary searches, URL host extraction, and named‑capture groups for extracting data.
The preg_match() function searches a subject string for a match to a given regular expression pattern. It takes the pattern, the subject, an optional matches array (filled with the full match and captured sub‑patterns), optional flags (e.g., PREG_OFFSET_CAPTURE ), and an optional offset to start the search.
It returns the number of matches (0 or 1) because it stops after the first match; preg_match_all() continues searching. On error, it returns FALSE .
Parameters :
pattern – the regular expression pattern (string).
subject – the input string to search.
matches – optional array that receives the results; $matches[0] contains the full match, $matches[1] the first captured group, and so on.
flags – optional flags such as PREG_OFFSET_CAPTURE to include the offset of each match.
offset – optional byte offset to start the search.
Example 1 – Simple case‑insensitive match
<?php
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>Example 2 – Word‑boundary match
<?php
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>Example 3 – Extract host name from a URL
<?php
$subject = "http://www.php.net/index.html";
if (preg_match('@^(?:http://)?([^/]+)@i', $subject, $matches)) {
$host = $matches[1];
// Get the last two parts of the host
if (preg_match('/[^.]+\.[^.]+$/', $host, $matches)) {
echo "domain name is: {$matches[0]}\n";
}
}
?>Example 4 – Named capture groups
<?php
$str = 'foobar: 2008';
preg_match('/(?P
\w+): (?P
\d+)/', $str, $matches);
print_r($matches);
?>Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.