PHP: Simple, Validate if string is hex?

27,696

Solution 1

Use function : ctype_xdigit

<?php
$strings = array('AB10BC99', 'AR1012', 'ab12bc99');
foreach ($strings as $testcase) {
    if (ctype_xdigit($testcase)) {
        echo "The string $testcase consists of all hexadecimal digits.\n";
    } else {
        echo "The string $testcase does not consist of all hexadecimal digits.\n";
    }
}
?> 

The above example will output:

  • The string AB10BC99 consists of all hexadecimal digits.
  • The string AR1012 does not consist of all hexadecimal digits.
  • The string ab12bc99 consists of all hexadecimal digits.

Solution 2

Another way without ctype or regex:

$str = 'string to check';

if (trim($str, '0..9A..Fa..f') == '') {
    // string is hexadecimal
}

Solution 3

Is there any reason not to match against a simple RE like "[0-9A-Fa-f]+"? (edit: possibly with a '^' at the beginning and '$' at the end to assure you've matched the whole string).

Solution 4

Add the case-insensitive 'i' flag

preg_match('/^[0-9a-f]+$/i', ...

Solution 5

Your input is too large. From the PHP manual of dexhex

The largest number that can be converted is 4294967295 in decimal resulting to "ffffffff"

So you'll be better off using a RegEx, which have already been supplied here by others.

Share:
27,696
oni-kun
Author by

oni-kun

Updated on April 25, 2020

Comments

  • oni-kun
    oni-kun about 4 years

    I have no clue how to validate this string. I am simply supplying an IV for an encryption, but can find no 1is_hex()1 or similar function, I can’t wrap my head around it! I read on a comment in the php documentation (user contrib. notes) this:

    if($iv == dechex(hexdec($iv))) {
      //True
    } else {
      //False
    }
    

    But that doesn't seem to work at all.. It only says false. If it helps my input of my IV would be this:

    92bff433cc639a6d