forked from bcit-ci/CodeIgniter
-
Notifications
You must be signed in to change notification settings - Fork 0
hexadecimal validation
Derek Jones edited this page Jul 5, 2012
·
5 revisions
Part of my project I needed hexadecimal validation so I write these function. You guys may need this too enjoy! Suggestion are welcome.
<?php
// ------------------------------------------------------------------------
/**
* Hexadecimal validation function
*
* Useful for validating hexadecimal value
*
* @access public
* @param string input string.
* @return Boolean
*/
function is_hex($entry)
{
$validChar=array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');// characters allowed in hex
$stringlen=strlen($entry);
$entry=strtoupper($entry); // lowercase characters? make uppercase
// Now scan string for illegal characters
for ($i=0;$i<$stringlen;$i++){
if(!in_array(charAt($entry,$i),$validChar)){
return false;}
} // end scanning loop
return true;
}
/**
* Javascript simalr charAt function
*
* Pick the string from the define position
* @access public
* @param string input string.
* @return 1 Character
*/
function charAt($str, $pos)
{
return (substr($str, $pos, 1));
}
?>
This helper funcrion can be changed for a simple regexp. So
<?php
// ------------------------------------------------------------------------
/**
* Hexadecimal validation function
*
* Useful for validating hexadecimal value
*
* @access public
* @param string input string.
* @return Boolean
*/
function is_hex($entry)
{
return (bool) preg_match ('/[^0-9a-fA-F]/', $entry);
}
?>