$var="10af4f4"; // All are hexadecimal chars or digits
$var="10af4g4"; // All or some are not hexadecimal chars
if(ctype_xdigit($var)){
echo " All are hexadecimal chars or digits ";
}else{
echo "All or some are not hexadecimal chars ";
}
Syntax
bool ctype_xdigit ( string $input_string )
$input_string : String to be checked.
ctype_xdigit() is a PHP filter function checks if all chars in the $input_string are hexadecimal or not. Any thing other than this if present then it return FALSE.
Hexadecimal is positional numeral system with base of 16. The chars it used are from 0 to 9 and from A to F ( lower or upper case ) .
You can change the value of the variable $var in above script and see the result. Decimal points are not allowed ( False ) in ctype_xdigit.
We can check the form data input by users directly by using ctype_xdigit function. Here is one example.
if(ctype_xdigit($_POST['var'])){
echo " All are hexadecimal chars or digits ";
}else{
echo "All or some are not hexadecimal chars or digits";
}
Checking array elements
$ar=array('abc','12ffff',123,'FF123','@12ff');
foreach ($ar as $var){
if(ctype_xdigit($var)){
echo " <b>$var</b> is hexadecimal number ";
}else{
echo " <b>$var</b> is NOT hexadecimal number ";
}
echo "<BR>";
}
Output
abc is hexadecimal number
12ffff is hexadecimal number
123 is NOT hexadecimal number
FF123 is hexadecimal number
@12ff is NOT hexadecimal number
Removing blank space before using
It is better to use string function trim to remove blank space present at starting and ending of the variable before using it. Users some time add blank space and this goes wrongly as not alphanumeric variable. Here is the modified script to remove blank space.
<?Php
$var=$_POST['var'];
$var=trim($var); // remove space at starting and ending of variable.
if(ctype_xdigit($var)){
echo " all are hexadecimal chars or digits ";
}else{ echo "All or some are not hexadecimal chars or digits";}
echo "<br><br>";//
if(!ctype_xdigit($var)){
echo " Inside if <br>";
}
?>
For easy understanding here is the form to submit data to above script