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
WaldoMonster
Forum Contributor
Posts: 225 Joined: Mon Apr 19, 2004 6:19 pm
Contact:
Post
by WaldoMonster » Sun Jan 29, 2006 10:54 am
How to check if a value is valid HEX?
Code: Select all
1234567890abcdef => valid
1234567890abcggg => legal
raghavan20
DevNet Resident
Posts: 1451 Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:
Post
by raghavan20 » Sun Jan 29, 2006 11:05 am
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 » Sun Jan 29, 2006 11:10 am
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!!!";
WaldoMonster
Forum Contributor
Posts: 225 Joined: Mon Apr 19, 2004 6:19 pm
Contact:
Post
by WaldoMonster » Sun Jan 29, 2006 11:42 am
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!!!";
raghavan20
DevNet Resident
Posts: 1451 Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:
Post
by raghavan20 » Sun Jan 29, 2006 11:55 am
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 » Sun Jan 29, 2006 5:03 pm
PHP will ignore the non-hex characters and do it's best to convert it to a valid hex