RE: [PHP4BETA] is string numeric
| From: | Lars Torben Wilson | Date: | Thu, 16 Mar 2000 10:56:41 +0000 |
| Subject: | RE: [PHP4BETA] is string numeric | ||
| References: | 1 2 | Groups: | php.version4 |
| Request: | Send a blank email to php-version4+get-12225@lists.php.net to get a copy of this message | ||
Harold writes:
>
> someone emailed me a solution with what i was looking for..
>
> $a="12345";
> if (eregi ("\D", $a)):
> // not only numbers in string
> else:
> // only numbers in string
> endif;
This won't work. \D is perl regexp syntax, not POSIX, so you'd need to
use [[:digit:]] or [0-9] instead of \D. Also, this just checks for the
existence of a digit in the string; it doesn't say anything about all
the elements being digits.
You could reverse the logic with the ^ operator to make it look for
any non-numeric data ([0-9] means "match any digit", and [^0-9] means
"match any non-digit").
<?php
$string = '123435';
if ( !ereg( '[^0-9]', $string ) ) {
echo "String is pure numeric.\n";
} else {
echo "String contains non-numeric data.\n";
}
?>
Alternatively, you could skip the regexp (which is moderately
expensive) altogether by simply casting the string to int, then
casting back to string. If it's still the same, then it's all numeric
since any non-numeric elements would be lost in the cast:
<?php
function is_numeric( $str ) {
return ( (string) (int) $str == $str );
}
echo is_numeric( $string ) ? "Yes" : "No" ;
?>
--
+----------------------------------------------------------------+
|Torben Wilson <torben@php.net> Netmill iTech|
|http://www.coastnet.com/~torben http://www.netmill.fi|
|Ph: 1 250 383-9735 torben@netmill.fi|
+----------------------------------------------------------------+