我有两个功能。IsOcta和isHex。似乎无法使 isHex 正常工作。
isHex() 中的问题是它不能省略原始字符串x23的 'x' 表示法。
原始十六进制字符串也可以是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 指导测试字符串中是否存在十六进制字符的内置函数。还要感谢 mario 提示使用 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
可能现在,这是对“十六进制”功能的简单证明吗?