validate dutch zipcodes with a regex in php

To validate Dutch zipcodes with a regex in PHP, you can use the following regular expression:

main.php
$zipcodeRegex = '/^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/';
51 chars
2 lines

This regex matches zipcodes that start with a digit between 1 and 9, followed by three digits between 0 and 9, followed by an optional whitespace character (\s), and finally two uppercase or lowercase letters.

Here is an example implementation:

main.php
function validateDutchZipcode($zipcode) {
    $zipcodeRegex = '/^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/';
    return preg_match($zipcodeRegex, $zipcode);
}

// Example usage
$zipcode = "1234AB";
if (validateDutchZipcode($zipcode)) {
    echo "Valid Dutch zipcode!";
} else {
    echo "Invalid Dutch zipcode.";
}
303 chars
13 lines

This function will return true for valid Dutch zipcodes and false for invalid zipcodes.

gistlibby LogSnag