[英]in_array function, why this doesn't work?
I'm trying to validate a string to an array of numbers. 我正在尝试将字符串验证为一组数字。 If the string only contains numbers then the function should validate, but in_array isn't working, any suggestions?
如果字符串只包含数字,那么函数应该验证,但是in_array不起作用,有什么建议吗?
$list = array(0,1,2,3,4,5,6,7,8,9);
$word = 'word';
$split = str_split($word);
foreach ($split as $s) {
if (!in_array($s, $list)) {
print 'asdf';
}
}
here is the class: 这是班级:
class Validate_Rule_Whitelist {
public function validate($data, $whitelist) {
if (!Validate_Rule_Type_Character::getInstance()->validate($data)) {
return false;
}
$invalids = array();
$data_array = str_split($data);
foreach ($data_array as $k => $char) {
if (!in_array($char, $whitelist)) {
$invalids[] = 'Invalid character at position '.$k.'.';
}
}
if (!empty($invalids)) {
$message = implode(' ', $invalids);
return $message;
}
return true;
}
}
in_array comparison with loosely typed values is somewhat strange. in_array与松散类型值的比较有点奇怪。 What would work in your case is:
在你的情况下会起作用的是:
$list = array('0','1','2','3','4','5','6','7','8','9');
$word = 'word';
$split = str_split($word);
foreach ($split as $s) {
if (!in_array($s, $list, true)) {
print 'asdf';
}
}
This compares strings with strings and results in no surprises. 这将字符串与字符串进行比较,结果毫无意外。 But , as noted in the comments already, this is quite wrong way to do things and it is much better to use filter_var() or regular expressions** to achieve what you're trying.
但是 ,正如评论中已经指出的那样,这是非常错误的做事方式,使用filter_var()或正则表达式**来实现你正在尝试的东西要好得多。
Something along the lines of this should work: 有些事情应该有效:
<?php
$validate_me = '123xyz';
if(preg_match("/[^0-9]/", $validate_me, $matches))
print "non-digit detected";
?>
it's ugly as sin but it works, no elegant solution here, just a double loop, if you see any problems please let me know 它是丑陋的,但它有效,这里没有优雅的解决方案,只是一个双循环,如果你看到任何问题请告诉我
$match = array();
foreach ($data_array as $k => $char) {
foreach ($whitelist as $w) {
if (!isset($match[$k])) {
if ($char === $w) {
$match[$k] = true;
}
}
}
if (!isset($match[$k]) || $match[$k] !== true) {
$invalids[$k] = 'Invalid character at position '.$k.'.';
}
}
update: add the $type = gettype ... settype($char, $type) to allow === to function correctly when checking for integers 更新:添加$ type = gettype ... settype($ char,$ type)以允许===在检查整数时正常运行
foreach ($data_array as $k => $char) {
foreach ($whitelist as $w) {
if (!isset($match[$k])) {
$type = gettype($w);
if (gettype($char) !== $type) {
settype($char, $type);
}
if ($char === $w) {
$match[$k] = true;
}
}
}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.