Is there a way to send parameters into a callback function without creating my own function first?

北城以北 提交于 2019-12-10 14:03:27

问题


I have an array of values that I would like to run through htmlspecialchars but with an argument such as this:

$param = htmlspecialchars($param, ENT_QUOTES);

The problem is, I have an array of values that I want to run htmlspecialchars on:

$array = array_map('htmlspecialchars', $array);

and I would like to know if there is a way to pass ENT_QUOTES into the array_map callback?

I can always use my own function that uses htmlspecialchars, but it would be nice if there was a way to do this already.


After the answer below, here is my end result:

$array = array_map('htmlspecialchars', $array, array_fill(0, count($array), ENT_QUOTES));

Which simply fills an array with as many values as $array has and it's filled with ENT_QUOTE.


回答1:


This should work if you pass a second array as parameter to array_map that will contain as many ENT_QUOTES elements as your number of elements in $array:

$quote_style = ENT_QUOTES;
$array = array('"',"'","''''''''''''\"");
$ent_quotes_array = array($quote_style, $quote_style, $quote_style);
$array = array_map('htmlspecialchars', $array, $ent_quotes_array);
print_r($array);

Or, a little bit more elegant:

$array = array('"',"'","''''''''''''\"");
$ent_quotes_array = array_fill(0, sizeof($array), ENT_QUOTES);
$array = array_map('htmlspecialchars', $array, $ent_quotes_array);



回答2:


Here is my output helper function...

function change_values_for_encode_output(&$item, $key) {
    $item = htmlentities($item, ENT_QUOTES);
}

function encode_output_vars($vars) {
    if(is_array($vars)) {
        array_walk_recursive($vars, 'change_values_for_encode_output');
        return $vars;
    }
    else {
        $vars = htmlentities($vars, ENT_QUOTES);
                    return $vars;
    }
}


来源:https://stackoverflow.com/questions/8454747/is-there-a-way-to-send-parameters-into-a-callback-function-without-creating-my-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!