Valid HEX?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
WaldoMonster
Forum Contributor
Posts: 225
Joined: Mon Apr 19, 2004 6:19 pm
Contact:

Valid HEX?

Post by WaldoMonster »

How to check if a value is valid HEX?

Code: Select all

1234567890abcdef => valid
1234567890abcggg => legal
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post by raghavan20 »

Code: Select all

if (TRUE === preg_match("/[^A-Fa-f0-9]/", $input_string))
	echo "Not a hexadecimal!!!";
Roja
Tutorials Group
Posts: 2692
Joined: Sun Jan 04, 2004 10:30 pm

Post 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!!!";
User avatar
WaldoMonster
Forum Contributor
Posts: 225
Joined: Mon Apr 19, 2004 6:19 pm
Contact:

Post 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!!!";
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post 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!!!";
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post 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
Post Reply