How can you check if a string contains only numbers in PHP?

To check if a string contains only numbers in PHP, you can use a regular expression to match the string against a pattern that allows only numeric characters. The regular expression pattern "\d+" can be used to match one or more digits in a string. By using the preg_match function in PHP, you can determine if the string contains only numbers.

$string = "12345";
if (preg_match('/^\d+$/', $string)) {
    echo "The string contains only numbers.";
} else {
    echo "The string does not contain only numbers.";
}