How to check if a string contains only digits in PHP

2 Answers

0 votes
$pattern = '/.*[^0-9].*/';

$s = "3762724";
echo (!preg_match($pattern, $s)) ? "yes\n" : "no\n";

$s = "3762724W";
echo (!preg_match($pattern, $s)) ? "yes\n" : "no\n";

$pattern = '/.*\D.*/';

$s = "83947592384";
echo (!preg_match($pattern, $s)) ? "yes\n" : "no\n";

$s = "930239WP";
echo (!preg_match($pattern, $s)) ? "yes\n" : "no\n";




/*
run:

yes
no
yes
no

*/

 



answered Jul 24, 2024 by avibootz
0 votes
<?php

$str = "3762724";
$b = ctype_digit($str);
echo $b ? 'true' : 'false';

echo "\n";

$str = "3762724W";
$b = ctype_digit($str);
echo $b ? 'true' : 'false';




/*
run:

true
false

*/

 



answered Jul 24, 2024 by avibootz
...