Codectionary / Developer documentation / PHP

PHP regular-expression captures

preg_match finds one regular-expression match and fills a captures array. Its result distinguishes a match (1), no match (0), and a regex error (false).

Syntax

preg_match($pattern, $subject, $matches)

Examples

PHP regular-expression captures

Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.

<?php
$result = preg_match('/\A([A-Z]+)-(\d+)\z/', 'INV-204', $parts);
if ($result === 1) {
    echo $parts[1], ':', $parts[2], PHP_EOL;
} elseif ($result === false) {
    throw new RuntimeException(preg_last_error_msg());
}
  1. Output: INV:204. Anchors require the entire subject to follow the invoice-code format.

Best practices

  • Use strict result comparisons and escape dynamic literal fragments with preg_quote. Keep untrusted patterns out of the regex engine.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading