Regex Basics
A regular expression is a pattern that describes text to search for. preg_match tests a string against a pattern and reports whether it matched.
preg_match answers 1 or 0
preg_match tests one pattern against one string. A match gives 1 and no match gives 0.
<?php
$text = "The cat sat on the mat";
echo preg_match("/cat/", $text), "\n";
echo preg_match("/dog/", $text), "\n";Three digits in a row match a code
\d matches one digit, and {3} asks for three digits in a row. The matched text lands in the matches array.
<?php
$text = "Your code is 482 today";
echo preg_match("/\d{3}/", $text, $matches), "\n";
echo $matches[0], "\n";preg_match_all counts and lists every number
preg_match_all keeps searching after the first match, and \d+ means one or more digits in a row. The matched texts land in an array in the order they were found.
<?php
$text = "Scores were 10, 25 and 7 today";
$count = preg_match_all("/\d+/", $text, $matches);
echo $count, "\n";
print_r($matches[0]);Example
<?php
$line = "Code 731 was filed in 2026";
preg_match("/\d{3}/", $line, $code);
preg_match("/\d{4}/", $line, $year);
echo $code[0], "\n";
echo $year[0], "\n";Key points
- preg_match returns 1 when the pattern matches and 0 when it does not.
- The pattern sits between two slash characters called delimiters.
- \d in a pattern matches one digit character.
- {3} after a part of a pattern means that part repeats exactly three times.
- preg_match_all finds every match in the string and returns how many there were.
In this example, the line holds a three-digit code and a four-digit year. The first preg_match call finds 731 with the three-digit pattern. The second call finds 2026 with the four-digit pattern. Each found text prints on its own line.
Note
preg_match stops at the first match, while preg_match_all keeps searching to the end of the string.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does preg_match("/\d{2}/", "Room 42") return?