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”.
Example 2 uses word boundaries \b to match only the whole word “web”.
Example 3 extracts the host name from a URL.
Example 4 shows named sub‑patterns to capture a name and a number.
\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.