php – isHex()和isOcta()函数

前端之家收集整理的这篇文章主要介绍了php – isHex()和isOcta()函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个功能. IsOcta和isHex.似乎无法使isHex正常工作.
isHex()中的问题是它不能省略原始字符串x23的’x’表示法.

原始十六进制srting也可以是D1CE.所以添加x然后比较不会.

是否有正确的isHex函数解决方案. isOcta也正确吗?

function isHex($string){
    (int) $x=hexdec("$string");     // Input must be a String and hexdec returns NUMBER
    $y=dechex($x);          // Must be a Number and dechex returns STRING
    echo "<br />isHex() - Hexa Number Reconverted: ".$y;       

    if($string==$y){
        echo "<br /> Result: Hexa ";
    }else{
        echo "<br /> Result: NOT Hexa";
    }   
    }


function IsOcta($string){
    (int) $x=octdec("$string");     // Input must be a String and octdec returns NUMBER
          $y=decoct($x);            // Must be a Number and decoct returns STRING
    echo "<br />IsOcta() - Octal Number Reconverted: ".$y;          

    if($string==$y){
    echo "<br /> Result: OCTAL";
    }else{
    echo "<br /> Result: NOT OCTAL";
    }

}

这是对函数调用

$hex    =   "x23";      // STRING 
$octa   =   "023";  // STRING 
echo "<br /    Original HEX = $hex | Original Octa = $octa <br /    ";

echo isHex($hex)."<br /    ";   
echo IsOcta($octa);

这是函数调用的结果:

Original HEX = x23 | Original Octa = 023 

isHex() - Hexa Number Reconverted: 23
Result: NOT Hexa

IsOcta() - Octal Number Reconverted: 23
Result: OCTAL

=====完整的答案====

感谢Layke指导内置函数,该函数测试HEXA DECIMAL字符是否存在于字符串中.还要感谢马里奥提供使用ltrim的提示.这两个函数都需要获得isHexa或者是要构建的十六进制函数.

—编辑功能

// isHEX function

function isHex($strings){

// Does not work as originally suggested by Layke,but thanks for directing to the resource. It does not omit 0x representation of a hexadecimal number. 
/*
foreach ($strings as $testcase) {
     if (ctype_xdigit($testcase)) {
        echo "<br /> $testcase - <strong>TRUE</strong>,Contains only Hex<br />";
    } else {
        echo "<br /> $testcase - False,Is not Hex";

   } 
}
*/

   // This works CORRECTLY
   foreach ($strings as $testcase) {
        if (ctype_xdigit(ltrim($testcase,"0x"))) {
           echo "<br /> $testcase - <strong>TRUE</strong>,Contains only Hex<br />";
       } else {
           echo "<br /> $testcase - False,Is not Hex";

      } 
   }
}

$strings = array('AB10BC99','AR1012','x23','0x12345678');
isHex($strings); // calling

可能现在,这是’十六进制’功能的傻瓜证明答案吗?

isHexadecimal?

PHP内置了十六进制函数.

请参阅此处的函数ctype_xdigit:http://uk1.php.net/ctype_xdigit

<?PHP
$strings = array('AB10BC99','ab12bc99');
foreach ($strings as $testcase) {
    if (ctype_xdigit($testcase)) {
        // TRUE : Contains only Hex
    } else {
        // False : Is not Hex
    }
}

isOctal?

并且为了确定数字是否为octal,您可以翻转和翻转.

function isOctal($x) {
    return decoct(octdec($x)) == $x;
}

猜你在找的PHP相关文章