Page 1 of 1

Hex code validation using preg_match()

Posted: Tue Jul 02, 2002 12:42 am
by protokol
I have a string which is 6 characters long (a hex code). Basically I want to have a function which returns true or false depending on if it finds a character other than 0-9 or A-F in the string.

Right now, the code that I am using looks like this:

Code: Select all

function validHex($hex) {
   return preg_match_all("/ї0-9a-fA-F]/", $hex, $results) == 6;
}
This function works, but seems like a bit much to check for an invalid character. First of all, I don't need $results to be returned containing the string information. The problem is that I can't seem to figure out any other way to validate the string besides this.

I would like to just use preg_match(), so if anyone can possibly help out with this problem, it would be greatly appreciated. Thanks!

Posted: Tue Jul 02, 2002 9:26 am
by twigletmac
The easiest thing to do would be the opposite of what you're currently doing, instead of matching all the characters that are correct do preg_match() to find any that aren't:

Something like,

Code: Select all

if (preg_match('/ї^0-9a-f]/i', $hex) || strlen($hex) > 6) {
    echo 'bad hex';
} else {
    echo 'good hex';
}
Mac

Posted: Tue Jul 02, 2002 2:53 pm
by protokol
Excellent, I knew it was something simple. Works great! Thanks!