Challenge 1 — Solution
Task: Write a pattern that matches a UK postcode in the simplified
format "AA1 1AA" (two letters, one digit, a space, one digit, two
letters). Test it with preg_match() against both a matching and a
non-matching string, echoing the result of each.
";
} else {
echo "'$valid' does not match the pattern.
";
}
if (preg_match($pattern, $invalid)) {
echo "'$invalid' matches the pattern.
";
} else {
echo "'$invalid' does not match the pattern.
";
}
?>
Output:
'SW1 1AA' matches the pattern.
'SW1A 1AA' does not match the pattern.
Notes:
- [A-Z]{2} matches exactly two uppercase letters, \d matches a single
digit, the literal space matches the space character, and the
pattern closes with another digit and two more letters - together
reproducing the simplified "AA1 1AA" shape exactly.
- ^ and $ anchor the pattern to the very start and end of the string,
ensuring the whole string must match this shape, not just some
substring buried inside a longer one.
- "SW1A 1AA" (a genuine, valid real-world UK postcode format) fails
this simplified pattern because it has an extra letter (A) after the
first digit - a deliberate illustration that this course's own
simplified pattern doesn't cover every real postcode variant, only
the basic shape described in the exercise.