typestar

Regex with preg_match in PHP

Pulling structured fields out of a log line with PCRE.

<?php
$log = "2026-08-02 14:03 GET /api/users 200";

if (preg_match('/^(\d{4})-(\d{2})-(\d{2})/', $log, $m)) {
    echo "year $m[1], month $m[2]\n";
}

// named capture groups read better than indexes
$pattern = '/(?<verb>GET|POST) (?<path>\S+) (?<status>\d{3})/';
if (preg_match($pattern, $log, $hit)) {
    echo "$hit[verb] $hit[path] -> $hit[status]\n";
}

echo preg_match_all('/\d+/', $log, $nums), " number runs\n";

How it works

  1. preg_match fills $m with the whole match and one entry per group.
  2. (?<verb>...) names a group, so $hit[verb] beats counting parentheses.
  3. preg_match_all returns how many times the pattern hit.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
412
Tokens
68
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 63 seconds.

Type this snippet

Step 3 of 3 in Strings & regex, step 15 of 27 in Language basics.

← Previous Next →