PHP preg_match() Function: Syntax, Parameters, Return Values, and Examples
This article explains the PHP preg_match() function, detailing its syntax, parameters, return values, and providing multiple code examples that demonstrate pattern matching, case‑insensitive searches, word boundaries, URL host extraction, and named sub‑patterns.
preg_match() executes a regular expression match on a subject string.
Parameters : string $pattern – the regex pattern. string $subject – the input string. array &$matches – optional array filled with the results. int $flags = 0 – optional flags such as PREG_OFFSET_CAPTURE. int $offset = 0 – optional start offset.
Return value : number of matches (0 or 1) or FALSE on error.
Example 1 demonstrates a case‑insensitive search for the word “PHP”.
<?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 uses word boundaries \b to match only the whole word “web”.
<?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 extracts the host name from a URL.
<?php
preg_match('@^(?:http://)?([^/]+)@i', "http://www.php.net/index.html", $matches);
$host = $matches[1];
echo "domain name is: $host
";
?>Example 4 shows named sub‑patterns to capture a name and a number.
<?php
$str = 'foobar: 2008';
preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);
print_r($matches);
?>Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
