PHP:简单,验证字符串是否为十六进制?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2643157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: Simple, Validate if string is hex?
提问by oni-kun
I have no clue how to validate this string. I am simply supplying an IV for an encryption, but can find no 1is_hex()1 or similar function, I can't wrap my head around it! I read on a comment in the php documentation (user contrib. notes) this:
我不知道如何验证这个字符串。我只是为加密提供了一个 IV,但是找不到 1is_hex()1 或类似的函数,我无法理解它!我阅读了 php 文档中的评论(用户贡献。注释):
if($iv == dechex(hexdec($iv))) {
//True
} else {
//False
}
But that doesn't seem to work at all.. It only says false. If it helps my input of my IV would be this:
但这似乎根本不起作用..它只是说假。如果它有助于我输入我的 IV 将是这样的:
92bff433cc639a6d
回答by Haim Evgi
Use function : ctype_xdigit
使用函数: ctype_xdigit
<?php
$strings = array('AB10BC99', 'AR1012', 'ab12bc99');
foreach ($strings as $testcase) {
if (ctype_xdigit($testcase)) {
echo "The string $testcase consists of all hexadecimal digits.\n";
} else {
echo "The string $testcase does not consist of all hexadecimal digits.\n";
}
}
?>
The above example will output:
上面的例子将输出:
- The string
AB10BC99consists of all hexadecimal digits. - The string
AR1012does not consist of all hexadecimal digits. - The string
ab12bc99consists of all hexadecimal digits.
- 该字符串
AB10BC99由所有十六进制数字组成。 - 该字符串
AR1012并非由所有十六进制数字组成。 - 该字符串
ab12bc99由所有十六进制数字组成。
回答by Jerry Coffin
Is there any reason not to match against a simple RE like "[0-9A-Fa-f]+"? (edit: possibly with a '^' at the beginning and '$' at the end to assure you've matched the whole string).
有什么理由不匹配像“[0-9A-Fa-f]+”这样的简单正则?(编辑:可能以 '^' 开头和 '$' 结尾以确保您已匹配整个字符串)。
回答by nggit
Another way without ctypeor regex:
没有ctype或的另一种方式regex:
$str = 'string to check';
if (trim($str, '0..9A..Fa..f') == '') {
// string is hexadecimal
}
回答by dahook
Add the case-insensitive 'i' flag
添加不区分大小写的“i”标志
preg_match('/^[0-9a-f]+$/i', ...
回答by dahook
The perfect way to check HEX string works from PHP 4 and above.
检查十六进制字符串的完美方法适用于 PHP 4 及更高版本。
<?php
function is_hex($hex_code) {
return @preg_match("/^[a-f0-9]{2,}$/i", $hex_code) && !(strlen($hex_code) & 1);
}
?>
回答by nikc.org
Your input is too large. From the PHP manual of dexhex
你的输入太大了。来自dexhex的PHP手册
The largest number that can be converted is 4294967295 in decimal resulting to "ffffffff"
可以转换的最大数字是十进制的 4294967295,结果为“ffffffff”
So you'll be better off using a RegEx, which have already been supplied here by others.
因此,您最好使用其他人已经在此处提供的 RegEx。
回答by paul.pech
This is also possible and quite simple
这也是可能的,而且很简单
$a="affe"; //is_hex
$b="a0bg"; //is_not_hex
if(is_numeric('0x'.$a)) echo 'is_hex';
else echo 'is_not_hex';
if(is_numeric('0x'.$b)) echo 'is_hex';
else echo 'is_not_hex';

