note 87113 modified in function.ctype-digit by danbrown
| From: | danbrown@php.net | Date: | Wed, 19 Nov 2008 22:02:06 +0000 |
| Subject: | note 87113 modified in function.ctype-digit by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-146730@lists.php.net to get a copy of this message | ||
Indeed, ctype_digit only functions correctly on strings. Cast your vars to string before you test
them. Also, be wary and only use ctype_digit if you're sure your var contains either a string
or int, as boolean true for ex will convert to int 1.
To be truly safe, you need to check the type of the var first. Here's a wrapper function that
improves upon ctype_digit's broken implementation:
<?php
// replacement for ctype_digit, to properly
// handle (via return value false) nulls,
// booleans, objects, resources, etc.
function ctype_digit2 ($str) {
return (is_string($str) || is_int($str) || is_float($str)) &&
ctype_digit((string)$str);
}
?>
If, like me, you're not willing to take a chance on ctype_digit having other problems, use this
version:
<?php
// replacement for ctype_digit, to properly
// handle (via return value false) nulls,
// booleans, objects, resources, etc.
function ctype_digit2 ($str) {
return (is_string($str) || is_int($str) || is_float($str)) &&
preg_match('/^\d+\z/', $str);
}
?>
--was--
Indeed, ctype_digit only functions correctly on strings. Cast your vars to string before you test
them. Also, be wary and only use ctype_digit if you're sure your var contains either a string
or int, as boolean true for ex will convert to int 1.
To be truly safe, you need to check the type of the var first. Here's a wrapper function that
improves upon ctype_digit's broken implementation:
<?
// replacement for ctype_digit, to properly
// handle (via return value false) nulls,
// booleans, objects, resources, etc.
function ctype_digit2 ($str) {
return (is_string($str) || is_int($str) || is_float($str)) &&
ctype_digit((string)$str);
}
?>
If, like me, you're not willing to take a chance on ctype_digit having other problems, use this
version:
<?
// replacement for ctype_digit, to properly
// handle (via return value false) nulls,
// booleans, objects, resources, etc.
function ctype_digit2 ($str) {
return (is_string($str) || is_int($str) || is_float($str)) &&
preg_match('/^\d+\z/', $str);
}
?>
http://php.net/manual/en/function.ctype-digit.php