php – isHex()和isOcta()函数
发布时间:2020-12-13 13:16:32 所属栏目:PHP教程 来源:网络整理
导读:我有两个功能. IsOcta和isHex.似乎无法使isHex正常工作. isHex()中的问题是它不能省略原始字符串x23的’x’表示法. 原始十六进制srting也可以是D1CE.所以添加x然后比较不会. 是否有正确的isHex函数解决方案. isOcta也正确吗? function isHex($string){ (int
我有两个功能. 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; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |