无法清理 PHP 中的所有数组值(使用 trim/htmlentities)

Can't sanitize all array values in PHP (using trim/htmlentities)

我创建了一个 PHP 函数,它通过使用 trim 和 htmlentities 清理所有数组值,除了那些其键存在于 $ignore[=24= 中的值] 大批。

function htmlentities_recursive( $input, $ignore ) {
    if( is_array( $input ) || is_object( $input ) ) {
        foreach ($input as $key => &$c) {
            if( !in_array( $key, $ignore ) ) {
                $c = htmlentities_recursive( $c, $ignore );
            }
        }
        return $input;
    }
    return htmlentities( trim( $input ) );
}

除数组的第一个值外,该函数大部分工作正常。例如,它适用于 $movies 数组的所有值,但第一个值 "Rear Window&" 除外(不清理此值),并按原样忽略具有键 'director' 的所有值。

$movies = array(
    array(
      "title" => "Rear Window&",
      "director" => "Alfred Hitc<hcock&",
      "year" => 1954
    ),
    array(
      "title" => "                            Full >Metal Jacket",
      "director" => "Sta<nley Kubrick&",
      "year" => 1987
    ),
    array(
      "title" => "Mean Stree&ts",
      "director" => "Ma>rtin S<corsese",
      "year" => 1973
    )
);
$testIgnore = ['foo','director','two'];

print_r(htmlentities_recursive($movies, $testIgnore));

结果是-

    Array
(
    [0] => Array
        (
            [title] => Rear Window&
            [director] => Alfred Hitc<hcock&
            [year] => 1954
        )

    [1] => Array
        (
            [title] => Full &gt;Metal Jacket
            [director] => Sta<nley Kubrick&
            [year] => 1987
        )

    [2] => Array
        (
            [title] => Mean Stree&amp;ts
            [director] => Ma>rtin S<corsese
            [year] => 1973
        )

)

我怎样才能清理第一个值?

in_array.

的调用是一个严格的比较问题

https://secure.php.net/manual/en/function.in-array.php

function htmlentities_recursive( $input, $ignore ) {
    if( is_array( $input ) || is_object( $input ) ) {
        foreach ($input as $key => &$c) {
            if( !in_array( $key, $ignore, true ) ) {
                $c = htmlentities_recursive( $c, $ignore );
            }
        }
        return $input;
    }
    return htmlentities( trim( $input ) );
}

外部数组的零索引导致整个第一个内部数组被跳过。显然 in_array(0, ['hello', 'world']) returns 正确,但 in_array(1, ['hello', 'world']) returns 错误。有趣的是,in_array(0, []) 是假的。