Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Simple, Validate if string is hex?

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 
like image 958
oni-kun Avatar asked Apr 15 '10 06:04

oni-kun


People also ask

How do you check if a string is hexadecimal in PHP?

PHP | ctype_xdigit() Function The ctype_xdigit() function in PHP used to check each and every character of string/text are hexadecimal digit or not. It return TRUE if all characters are hexadecimal otherwise return FALSE .

How do you check if a string is a valid hex color?

The length of the hexadecimal color code should be either 6 or 3, excluding '#' symbol. For example: #abc, #ABC, #000, #FFF, #000000, #FF0000, #00FF00, #0000FF, #FFFFFF are all valid Hexadecimal color codes.

Is Hex valid?

Yes, in hexadecimal, things like A, B, C, D, E, and F are considered numbers, not letters. That means that 200 is a perfectly valid hexadecimal number just as much as 2FA is also a valid hex number.


2 Answers

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.
like image 103
Haim Evgi Avatar answered Sep 28 '22 07:09

Haim Evgi


Another way without ctype or regex:

$str = 'string to check';  if (trim($str, '0..9A..Fa..f') == '') {     // string is hexadecimal } 
like image 29
nggit Avatar answered Sep 28 '22 07:09

nggit