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
preg_matchfills$mwith the whole match and one entry per group.(?<verb>...)names a group, so$hit[verb]beats counting parentheses.preg_match_allreturns how many times the pattern hit.
Keywords and builtins used here
echoifpreg_matchpreg_match_all
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.
Step 3 of 3 in Strings & regex, step 15 of 27 in Language basics.