Page 1 of 1

Valid HEX?

Posted: Sun Jan 29, 2006 10:54 am
by WaldoMonster
How to check if a value is valid HEX?

Code: Select all

1234567890abcdef => valid
1234567890abcggg => legal

Posted: Sun Jan 29, 2006 11:05 am
by raghavan20

Code: Select all

if (TRUE === preg_match("/[^A-Fa-f0-9]/", $input_string))
	echo "Not a hexadecimal!!!";

Posted: Sun Jan 29, 2006 11:10 am
by Roja
raghavan20 wrote:

Code: Select all

if (TRUE === preg_match("/[^A-Fa-f0-9]/", $input_string))
	echo "Not a hexadecimal!!!";
Actually, in many systems, hex is case sensitive - it must be lowercase.

Code: Select all

if (TRUE === preg_match("/[^a-f0-9]/", $input_string))
	echo "Not a hexadecimal!!!";

Posted: Sun Jan 29, 2006 11:42 am
by WaldoMonster
Thanks for the help.

I have made a small change to get it working.
preg_match returns a value not TRUE or FALSE.
So the === must be changed in ==.

Code: Select all

if (TRUE == preg_match("/[^A-Fa-f0-9]/", $input_string)) echo "Not a hexadecimal!!!";

Posted: Sun Jan 29, 2006 11:55 am
by raghavan20
I was not really expecting that behavior. Check for zero and one for TRUE and FALSE respectively. It also says that if there is an unexpected during validation then it will return a FALSE....so the better expression would be...

Code: Select all

$returnValue =  preg_match("/[^A-Fa-f0-9]/", $input_string) ;
if ( $returnValue == 0  || returnValue === FALSE )
echo "Not a hexadecimal!!!";

Posted: Sun Jan 29, 2006 5:03 pm
by josh

Code: Select all

dechex(hexdec('AF'))
PHP will ignore the non-hex characters and do it's best to convert it to a valid hex