PHP preg_match
Validate a whole classroom code with one capital ASCII letter and two digits.
A simple example
preg_match
- Start with "12" and the pattern ^[0-9]+$
- Do this Match the whole string
- Result Match
Syntax
preg_match("/\\A[A-Z][0-9]{2}\\z/", $value) === 1
Run these examples in PHP
Save one example at a time as lesson.php. Use PHP 8.2 or later.
php lesson.phpAccept a printed seat identifier
An exam supervisor scans a printed seat code. Accept a label that follows the required letter-and-digit pattern; the scanner must consume the entire code before confirming the seat.
<?php
$value = "B12";
echo ((preg_match("/\\A[A-Z][0-9]{2}\\z/", $value) === 1) ? "yes" : "no"), PHP_EOL;
yes
All three characters meet the pattern.
Reject a seat code with a suffix
A classroom scanner expects a seat identifier in a specific format. Validate the whole field so an otherwise valid prefix cannot admit stray characters at the end.
<?php
$value = "B12x";
echo ((preg_match("/\\A[A-Z][0-9]{2}\\z/", $value) === 1) ? "yes" : "no"), PHP_EOL;
no
The extra letter is outside the allowed format.
Validate a sample label
A lab assistant scans a four-character sample code. The form accepts exactly two capital ASCII letters followed by two digits. Does the complete entry meet that rule?
What to watch for
Some regex APIs search for an occurrence. Use a full-match API or explicit whole-input anchors.