Easy Tutorial
❮ Pdostatement Getcolumnmeta Func Xml Parser Set Option ❯

PHP preg_match() Function

PHP Regular Expressions (PCRE)

The preg_match function is used to perform a regular expression match.

Syntax

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

Searches the subject string for a match to the regular expression given in pattern.

Parameter Description:

Return Value

Returns the number of times pattern matches. This will be either 0 times (no match) or 1 time, because preg_match() will stop searching after the first match. preg_match_all() differs in that it continues to search until the end of the subject. If an error occurs, preg_match() returns FALSE.

Examples

Search for the text string "php":

<?php
// The "i" after the pattern delimiter indicates a case-insensitive search
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.";
}
?>

Execution result is as follows:

A match was found.

Search for the word "web"

<?php
/* The \b in the pattern indicates a word boundary, so only the distinct word "web" is matched, and not a word partial like "webbing" or "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.\n";
} else {
    echo "A match was not found.\n";
}

if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
    echo "A match was found.\n";
} else {
    echo "A match was not found.\n";
}
?>

Execution result is as follows:

A match was found.
A match was not found.

Extract the domain name from a URL

<?php
// Get the host name from the URL
preg_match('@^(?:http://)?([^/]+)@i',
    "http://www.tutorialpro.org/index.html", $matches);
$host = $matches[1];

// Get the last two segments of the host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>

Execution result is as follows:

domain name is: tutorialpro.org

Using named subgroups

<?php

$str = 'foobar: 2008';

preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

/* The following example works in PHP 5.2.2 (PCRE 7.0) or newer, however, for backward compatibility, the above method is recommended. */
// preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);

print_r($matches);

?>

Execution result is as follows:

Array
(
    [0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)
[0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)

PHP PCRE (Perl Compatible Regular Expressions)

❮ Pdostatement Getcolumnmeta Func Xml Parser Set Option ❯