W3docs

PHP sandbox

PHP preg_match() Online

Test a PCRE pattern with PHP itself and see the return value plus the full $matches array. Runs on real PHP 8.2 on our server when you press Run.

preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int|false

Runs on our server: your input is sent to w3docs and executed by PHP 8.2 in a sandbox with no network. Do not paste passwords or personal data.

Samples

With delimiters and modifiers, for example /^\d+$/i or #path/(\w+)#.

$flags

In bytes.

48 / 6,000 bytes of input · limit 6,000 bytes (about 6,000 characters)

Result

Press Run (or Ctrl+Enter) to call preg_match() on PHP 8.2. The typed result appears here.

Equivalent PHP

<?php
$result = preg_match('/(\\d{4})-(\\d{2})-(\\d{2})/', 'Released on 2024-03-15.', $matches);
var_dump($result, $matches);

About preg_match()

preg_match() searches a string for the first match of a PCRE pattern. It returns 1 when it finds one, 0 when it does not, and false when the pattern itself is broken.

The pattern needs delimiters, such as /.../ or #...#, with modifiers after the closing one (/abc/i). Captured groups land in $matches: index 0 is the whole match, then one entry per group, plus named keys for (?<name>...) groups.

PREG_OFFSET_CAPTURE turns each entry into a [text, byte offset] pair, and PREG_UNMATCHED_AS_NULL reports groups that did not take part as null instead of an empty string.

Worked example

Two capture groupsphp
preg_match('/(\d+)-(\d+)/', 'ab 12-34 cd', $m);
// $m = ['12-34', '12', '34']
0 is not falsephp
if (preg_match('/x/', 'abc') === false) {
    echo preg_last_error_msg(); // only for real errors
}

Compare with === so that "no match" (0) is not mistaken for an error (false).

Frequently asked questions

Why does preg_match() return false?

The pattern failed to compile (a warning names the problem and offset) or matching hit a PCRE limit, which preg_last_error_msg() reports.

Do I need delimiters?

Yes. PHP patterns are written as /pattern/flags. Without them PHP warns "Delimiter must not be alphanumeric, backslash, or NUL" and returns false.

Are offsets in characters or bytes?

Bytes. Add the u modifier for UTF-8 patterns, but offsets stay in bytes.

Is my input sent to a server?

Yes. These pages run real PHP 8.2 on the w3docs server, so the text you enter is sent there to run, in a sandbox with no network access. Do not paste passwords, keys or personal data.

How much input can I send?

Up to 6,000 bytes across all text fields, which is about 6,000 characters of plain text (accented letters and emoji take 2 to 4 bytes). Larger input is refused before anything is sent.