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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP preg_match() Function: Syntax, Parameters, Return Values, and Examples

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);
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backendregexpattern-matchingphp-functionspreg_match
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.