PHP Regular Expressions: preg_match, Replace, Split, and Grep

Last updated: August 25, 2026.

PHP’s PCRE functions search and transform text using regular-expression patterns. Use them when the rule is genuinely pattern-based; for a literal substring or replacement, str_contains() and str_replace() are clearer.

Pattern structure

A PHP pattern uses delimiters around the expression and optional modifiers after it. In /^order-(d+)$/i, the anchors require the whole subject to match, d+ captures digits, and i enables case-insensitive matching.

ConstructMeaning
^, $Start and end anchors
.Any character except newline by default
[A-Z]One character from a class or range
*, +, ?Zero or more, one or more, zero or one
(...)Capturing group
|Alternative

Match and capture values

$subject = 'Order-4821';
$pattern = '/^order-(?<id>\d+)$/i';

$result = preg_match($pattern, $subject, $matches);

if ($result === 1) {
    echo $matches['id']; // 4821
} elseif ($result === false) {
    throw new RuntimeException(preg_last_error_msg());
}

Find every match

$text = 'Items: AB-120, CD-450, EF-900';
preg_match_all('/\b[A-Z]{2}-\d{3}\b/', $text, $matches);
print_r($matches[0]);

Replace with a callback

$result = preg_replace_callback(
    '/\b[a-z]+\b/i',
    static fn(array $match): string => strtoupper($match[0]),
    'PHP regular expressions'
);

Split and filter

$keywords = preg_split('/[\s,]+/', 'php, regex patterns');
$names = ['Andrew', 'John', 'Peter', 'Nadia'];
$aToM = preg_grep('/^[a-m]/i', $names);

Practical safeguards

  • Add the u modifier when the pattern and subject are valid UTF-8 and Unicode behavior is intended.
  • Wrap untrusted literal text with preg_quote() before inserting it into a pattern.
  • Avoid ambiguous nested repetition on long untrusted input.
  • Check strictly for false; no match and an invalid pattern are different outcomes.
  • Use filter_var($email, FILTER_VALIDATE_EMAIL) for ordinary email-address validation.

Function signatures and pattern syntax are listed in the PHP PCRE manual.

admin

admin

Leave a Reply

Your email address will not be published.