How can preg_match be used to validate a string with exactly 9 digits in PHP?

To validate a string with exactly 9 digits in PHP using preg_match, you can use a regular expression pattern that matches exactly 9 digits. This pattern can be ^\d{9}$ where ^ signifies the start of the string, \d matches any digit, {9} specifies to match exactly 9 occurrences of the preceding element, and $ signifies the end of the string. By using preg_match with this pattern, you can easily validate if a string contains exactly 9 digits.

$string = "123456789"; // String to validate

if (preg_match('/^\d{9}$/', $string)) {
    echo "String contains exactly 9 digits.";
} else {
    echo "String does not contain exactly 9 digits.";
}