我有两个函数,一个是IsOcta,一个是isHex。但isHex似乎无法正常工作。
isHex()中的问题在于它无法省略原始字符串x23的'x'表示法。 原始十六进制字符串还可以是D1CE 。 因此,添加x然后进行比较是不行的。
是否有正确的解决方案来解决isHex函数的问题?另外isOcta是否正确?
也许现在,这是“十六进制”函数的绝对正确答案吗?
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或is十六进制函数。
--- 编辑后的函数 ---
// 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
也许现在,这是“十六进制”函数的绝对正确答案吗?
isOctal(0123)
=>false
,isOctal('123')
=>true
。它适用于字符串作为输入,但只告诉您一个字符串是否可能表示一个八进制数,而不是它是否会被PHP识别为八进制数。 - Adelmar