0

可能重复:
PHP 不区分大小写的 in_array 函数

我正在制作一个函数来通过一个$input变量和一个$whitelist变量来验证输入。两者都是字符串,函数解析$whitelist变量并将其转换为字符数组以在字符串上使用。

由于某种原因,该in_array函数无法区分小写字母和大写字母(至少我认为这是正在发生的事情)。

代码链接:http: //pastebin.com/eadAV7gg

4

1 回答 1

0

Why not match against the lowercase value of the letter. If you match it in the if statement, then you don't have to worry about changing the actual $input string:

foreach ($inputArray as $key => $value)
{
    foreach ($whitelistArray as $key2 => $value2)
    {
        if (in_array(strtolower($value), $whitelistArray))
        {
            //Do nothing, check passed
        }
        else
        {
            unset($inputArray[$key]);
        }
    }
}

A much shorter version of what you have could be accomplished with:

$input = "ATTT";
$whitelist = "abcdefghijklmnopqrstuvwxyz";
$output = '';

for($x=0; $x<strlen($input);$x++){
    if(stristr($whitelist,substr(strtolower($input),$x,1))){
        $output .= substr($input,$x,1);
    }
}
echo $output;

Or to implement as a function:

function whitelist_string($input=''){

    $whitelist = "abcdefghijklmnopqrstuvwxyz";
    $output = '';

    for($x=0; $x<strlen($input);$x++){
        if(stristr($whitelist,substr(strtolower($input),$x,1))){
            $output .= substr($input,$x,1);
        }
    }
    return $output;
}

echo whitelist_string('ATTT').'<br>';
echo whitelist_string('Hello88 World!').'<br>';
于 2013-01-29T21:37:12.560 回答