Sunday, April 29, 2012

Is_Hex Function for Determining if a String is Hex-Compatible in PHP

I wanted an Is_hex function that does the same as is_numeric, except for hexadecimal.  Here's one with decent efficiency that uses direct iteration.  $result stores the result as a TRUE/FALSE string (which can be changed to bool, depending on how you want to implement it), and $string_to_test is the string of possible-hex values you want to test.

<?php

    $result = "TRUE";
   
    $testable_string = strtolower($string_to_test);
    $testable_string_length = strlen($string_to_test);
   
    for($i_string = 0; $i_string < $testable_string_length; $i_string++)
    {
        $current_value_to_test = $testable_string[$i_string];
       
        if(    ($current_value_to_test != "0")        &&
            ($current_value_to_test != "1")        &&
            ($current_value_to_test != "2")        &&
            ($current_value_to_test != "3")        &&
            ($current_value_to_test != "4")        &&
            ($current_value_to_test != "5")        &&
            ($current_value_to_test != "6")        &&
            ($current_value_to_test != "7")        &&
            ($current_value_to_test != "8")        &&
            ($current_value_to_test != "9")        &&
            ($current_value_to_test != "a")        &&
            ($current_value_to_test != "b")        &&
            ($current_value_to_test != "c")        &&
            ($current_value_to_test != "d")        &&
            ($current_value_to_test != "e")        &&
            ($current_value_to_test != "f")        )
        {
            $result = "FALSE";
            $i_string = $testable_string_length;
        }
    }

?>

Official Function Page: http://php.net/manual/en/function.is-numeric.php

// Note: All code appearing on the PHP Revolution blog by the blog owner is released under the Hacktivismo Enhanced-Source Software License Agreement (HESSLA), unless otherwise noted.  http://www.hacktivismo.com/about/hessla.php

No comments:

Post a Comment