How can regular expressions be used to ensure that a number in PHP has a specific format, such as being 4 digits long?

Regular expressions can be used in PHP to ensure that a number has a specific format by defining a pattern that the number must match. To ensure that a number is exactly 4 digits long, we can use the regular expression pattern /^\d{4}$/ which specifies that the number must consist of exactly 4 digits.

$number = "1234";

if (preg_match("/^\d{4}$/", $number)) {
    echo "Number is 4 digits long.";
} else {
    echo "Number is not 4 digits long.";
}