Hex code validation using preg_match()

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
protokol
Forum Contributor
Posts: 353
Joined: Fri Jun 21, 2002 7:00 pm
Location: Cleveland, OH
Contact:

Hex code validation using preg_match()

Post 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!
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post 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
User avatar
protokol
Forum Contributor
Posts: 353
Joined: Fri Jun 21, 2002 7:00 pm
Location: Cleveland, OH
Contact:

Post by protokol »

Excellent, I knew it was something simple. Works great! Thanks!
Post Reply