Php isHex()和isOcta()函数
我有两个功能IsOcta和isHex。似乎无法使isHex正常工作。Php isHex()和isOcta()函数,php,hex,octal,Php,Hex,Octal,我有两个功能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=dech
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";
}
}
====完整答案====
感谢Layke指导测试字符串中是否存在十六进制字符的内置函数。还感谢mario给出使用ltrim的提示。这两个函数都是获得isHexa所必需的,或者是要构建的十六进制函数
---编辑功能--
//isHEX函数
函数isHex($strings){
//不象Layke最初建议的那样工作,但感谢您指向资源。它没有省略十六进制数的0x表示。
/*
foreach($testcase形式的字符串){
if(ctypexdigit($testcase)){
echo“
$testcase-TRUE,仅包含十六进制
”;
}否则{
echo“
$testcase-False,不是十六进制”;
}
}
*/
//这是正确的
foreach($testcase形式的字符串){
if(ctypexdigit(ltrim($testcase,“0x”)){
echo“
$testcase-TRUE,仅包含十六进制
”;
}否则{
echo“
$testcase-False,不是十六进制”;
}
}
}
$strings=array('AB10BC99','AR1012','x23','0x12345678');
isHex($strings);//使命感
也许现在,这就是“is hexadecimal”函数的傻瓜式答案吗?isHexadecimal?
PHP内置了十六进制函数
请参见此处的函数ctype\xdigit
:
您可以使用then清理输入字符串。在进行第一次转换之前,只需添加:
$string = ltrim($string, "0x");
将删除前导零(不需要)和x
字符。isHexadecimal::=
ctype_xdigit($testString)
等总量::=
preg_match('/^[0-7]+$/', $testString);
谢谢创造了奇迹。只需要Mario的输入就可以得到正确的函数。请参阅--编辑的函数--上面的部分错误答案。对于八进制测试“007”。这个答案有点误导
isotal(0123)
=>false
,isotal('123')
=>true
。它使用字符串作为输入,但只告诉您字符串是否可以表示八进制,而不是PHP是否会将其识别为八进制。谢谢,需要您输入ltrim来为Layke的提示添加最终形状。
<?php
$strings = array('AB10BC99', 'AR1012', 'ab12bc99');
foreach ($strings as $testcase) {
if (ctype_xdigit($testcase)) {
// TRUE : Contains only Hex
} else {
// False : Is not Hex
}
}
function isOctal($x) {
return decoct(octdec($x)) == $x;
}
$string = ltrim($string, "0x");
ctype_xdigit($testString)
preg_match('/^[0-7]+$/', $testString);