Hello Friends Today, through this tutorial, I will tell you How do you check if a string contains only numeric characters in PHP With Example? You can check if a string contains only numeric characters in PHP using regular expressions or built-in functions. Here’s an example using both approaches:
Using regular expressions:
<?php $string = "12345"; if (preg_match('/^[0-9]+$/', $string)) { echo "The string contains only numeric characters."; } else { echo "The string contains non-numeric characters."; } ?>
Using built-in functions:
<?php $string = "12345"; if (ctype_digit($string)) { echo "The string contains only numeric characters."; } else { echo "The string contains non-numeric characters."; } ?>
Both of these examples will output “The string contains only numeric characters.” since the string “12345” contains only numeric characters. If you change the string to something like “12345a”, it will output “The string contains non-numeric characters.”