PHP:如何在数组数组上执行 htmlspecialchar()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2002710/
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: how to perform htmlspecialchar() on an array-of-arrays?
提问by TeddyR
How do I run the PHP function htmlspecialchars()on an array of array objects?
如何htmlspecialchars()在数组对象数组上运行 PHP 函数?
I have the following code:
我有以下代码:
$result_set = Array
(
[0] => Array
(
[home_id] => 1
[address] => 4225 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 76798
)
[1] => Array
(
[home_id] => 8
[address] => 4229 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 75093
)
);
// this doesn't work since $result_set is an array of arrays and htmlspecialchars is expecting a string
htmlspecialchars($result_set, ENT_QUOTES, 'UTF-8'));
UPDATE:
更新:
Please note that even though there are quite a few answers below, none of them work for an array-of-arrays. The answers below only work for simple arrays.
请注意,尽管下面有很多答案,但它们都不适用于数组数组。下面的答案仅适用于简单数组。
I've tried the following, but it doesn't work:
我尝试了以下方法,但不起作用:
array_walk_recursive($result_set, "htmlspecialchars", array(ENT_QUOTES,'UTF-8'))
I get the following error: htmlspecialchars() expects parameter 2 to be long, string given
我收到以下错误: htmlspecialchars() expects parameter 2 to be long, string given
UPDATE 2
更新 2
When I try:
当我尝试:
function cleanOutput(&$value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
print_r($result_set);
print('-------');
print_r(array_walk_recursive($result_set, "cleanOutput"));
I get the following, undesired, output:
我得到以下不想要的输出:
Array
(
[0] => Array
(
[home_id] => 1
[address] => 4225 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 76798
)
[1] => Array
(
[home_id] => 8
[address] => 4229 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 75093
)
)
-------1
UPDATE 3
更新 3
When I try:
当我尝试:
function cleanOutput(&$value) {
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
$result_set = Array
(
[0] => Array
(
[home_id] => 1
[address] => 4225 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 76798
)
[1] => Array
(
[home_id] => 8
[address] => 4229 Nasmyth Dr
[city] => Plano
[state] => TX
[zip] => 75093
)
);
$cleanedOutput = array();
foreach ($result_set as $rs) {
$cleaned[] = array_map("cleanOutput", $rs);
}
print_r($cleanedOutput);
I get the following, undesired, results:
我得到以下不想要的结果:
{'homes' : []}
回答by Sampson
You can use array_map()to run that method on each entry.
您可以使用array_map()在每个条目上运行该方法。
$cleaned = array_map("htmlspecialchars", $myArray);
If you need to pass arguments to htmlspecialchars(), you can substitute it for your own custom function:
如果您需要将参数传递给htmlspecialchars(),您可以将其替换为您自己的自定义函数:
function myFunc($a) {
return htmlspecialchars($a, ENT_QUOES);
}
$cleaned = array_map("myFunc", $myArray);
Considering the fact that you're dealing with an array of arrays, and not an array of strings, you would need to cycle through the outer-array to get to your strings:
考虑到您正在处理数组数组而不是字符串数组这一事实,您需要循环遍历外部数组以获取字符串:
$cleaned = array();
foreach ($result_set as $rs) {
foreach ($rs as $r) {
$cleaned[] = array_map("htmlspecialchars", $r);
}
}
Or, you could use array_walk_recursive():
或者,您可以使用array_walk_recursive():
array_walk_recursive($myArray, "htmlspecialchars");
Note that this method changes the $myArray object by reference, so there's no need to assign the output to a new variable.
请注意,此方法通过引用更改 $myArray 对象,因此无需将输出分配给新变量。
回答by JW.
function filter(&$value) {
$value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
array_walk_recursive($result_set, "filter");
print_r($result_set);
回答by JAL
You may wish to use array_map as Jonathon Sampson suggested, another alternative is array_walk
您可能希望按照 Jonathon Sampson 的建议使用 array_map,另一种选择是array_walk
The difference is that array_map returns a copy of the array with the function applied to each element, while array_walk operates directly on the array you supply.
不同之处在于 array_map 返回数组的副本,该函数应用于每个元素,而 array_walk 直接对您提供的数组进行操作。
回答by wutter
Made way to make it work for multi-dimensional arrays:
使其适用于多维数组的方法:
function secure($val) {
return (is_array($val))?array_map('secure',$val):htmlspecialchars($val, ENT_QUOTES, 'UTF-8');
}
It works, that it calls its-self on array without last used array and if its not an array, it passes it to htmlspecialchars function.
它可以工作,它在没有最后使用的数组的情况下在数组上调用它自己,如果它不是数组,它将它传递给 htmlspecialchars 函数。
Input: Array ( [0] => test< [1] => Array ( [test>] => <test?> ) [2] => Array ( [0] => test [1] => > [2] => Array ( [0] => bigtest<> ) ) )
输入: Array ( [0] => test< [1] => Array ( [test>] => <test?> ) [2] => Array ( [0] => test [1] => > [2] => Array ( [0] => bigtest<> ) ) )
Output: Array ( [0] => test< [1] => Array ( [test>] => <test?> ) [2] => Array ( [0] => test [1] => > [2] => Array ( [0] => bigtest<> ) ) )
输出: Array ( [0] => test< [1] => Array ( [test>] => <test?> ) [2] => Array ( [0] => test [1] => > [2] => Array ( [0] => bigtest<> ) ) )
回答by Anthony Hatzopoulos
A lot of the answers on this page are either insufficient, outdated, or use the wrong parameters for array_mapor array_walk_recursive. Here's a function that will fix all scalar values in an array recursively.
此页面上的许多答案要么不充分、过时,要么对array_map或array_walk_recursive使用了错误的参数。这是一个将递归修复数组中所有标量值的函数。
htmlspecialchars_recursive()
htmlspecialchars_recursive()
<?php
function htmlspecialchars_recursive ($input, $flags = ENT_COMPAT | ENT_HTML401, $encoding = 'UTF-8', $double_encode = false) {
static $flags, $encoding, $double_encode;
if (is_array($input)) {
return array_map('htmlspecialchars_recursive', $input);
}
else if (is_scalar($input)) {
return htmlspecialchars($input, $flags, $encoding, $double_encode);
}
else {
return $input;
}
}
$test = array(
0 => array(
'test-1' => 'testing <p>html tag</p> will be fixed',
'test-2' => '® valid and will be left intact',
'test-3' => '? 2080 kept intact'
),
1 => array(
'test-4' => array(
'test-5' => 'deeper fix on <p>html tag</p> test',
'test-6' => '® will be left intact',
'test-7' => '? 2080 kept intact'
)
)
);
print_r(htmlspecialchars_recursive($test));
?>
Output
输出
Array
(
[0] => Array
(
[test-1] => testing <p>html tag</p> will be fixed
[test-2] => ® valid and will be left intact
[test-3] => ? 2080 kept intact
)
[1] => Array
(
[test-4] => Array
(
[test-5] => deeper fix on <p>html tag</p> test
[test-6] => ® will be left intact
[test-7] => ? 2080 kept intact
)
)
)
回答by Tyson of the Northwest
You don't need to create your own function if you are passing multiple arguments to the called back function.
如果将多个参数传递给回调函数,则无需创建自己的函数。
According to php.net:
根据php.net:
array array_map ( callback $callback , array $arr1 [, array $... ] )
array array_map ( callback $callback , array $arr1 [, array $... ] )
So that means if you want to pass multiple arguments you should just pass:
所以这意味着如果你想传递多个参数,你应该只传递:
$clean_array = array_map("htmlspecialchars", $myArray, array(ENT_QUOTES, 'UTF-8'));
but for some reason this doesn't work for me.
但由于某种原因,这对我不起作用。
But this seems to does, don't ask me why.
但这似乎确实如此,别问我为什么。
$clean_array = array_map("htmlspecialchars", $myArray, array(ENT_QUOTES), array('UTF-8'));
回答by Anthony
If you want to use array_map and pass the function arguments, you can create your own function and use that as the callback:
如果您想使用 array_map 并传递函数参数,您可以创建自己的函数并将其用作回调:
function cleanhtml($dirtyhtml) {
return htmlspecialchars($dirtyhtml, UTF-8);
}
$cleaned = array_map("cleanhtml", $myArray);
回答by venkatskpi
Validation Class function
验证类函数
function htmlspecialchars_recursive ($input, $flags = ENT_COMPAT | ENT_HTML401, $encoding = 'UTF-8', $double_encode = false) {
static $flags, $encoding, $double_encode;
if (is_array($input)) {
return array_map(array($this, 'htmlspecialchars_recursive'), $input);
}
else if (is_scalar($input)) {
return htmlspecialchars($input, $flags, $encoding, $double_encode);
}
else {
return $input;
}
}
Details:
细节:
$input = your input array() or scalar types like integer, float, string or boolean.
$flags = PHP Available flags constant description here
$encoding = encoding type default: UTF-8
$double_encode = based on your needs, you can used. TURE or FALSE
$input = 您的输入 数组() 或标量类型,如整数、浮点数、字符串或布尔值。
$flags = PHP 可用标志常量描述在这里
$encoding = 编码类型默认值:UTF-8
$double_encode = 根据你的需要,你可以使用。TRUE 或 FALSE
Function call
函数调用
//It will convert htmlentities
$param = $this->htmlspecialchars_recursive($_REQUEST);
// print_r($param);
Output:
输出:
/*
array(
[whyiitgnq] => <ul><li><b>teste</b></li><li><b>tetst</b></li></ul><div><i><u>tets</u></i></div><div>tets</div><ol><li><b>tetst</b></li><li><b>tetst</b></li><li><b>test</b></li></ol>
[_wysihtml5_mode] => 1
[aid] => 12695
)
*/
回答by dougd_in_nc
Here's another generic version that uses array_walk and behaves in the way that htmlspecialchars does with respect to parameters.
这是另一个使用 array_walk 的通用版本,其行为方式与 htmlspecialchars 对参数的处理方式相同。
function htmlspecialchars_r($string,
int $flags = ENT_COMPAT | ENT_HTML401,
string $encoding = null,
bool $double_encode = true )
{
if ($encoding === null)
{
$encoding = ini_get("default_charset");
}
$filter = function(&$value, $flags, $params) {
$value = htmlspecialchars($value, $params['flags'], $params['encoding'], $params['double_encode']);
};
array_walk_recursive($string, $filter,
array(
'flags' => $flags,
'encoding' => $encoding,
'double_encode' => $double_encode,
)
);
return $string;
}
回答by bortunac
function htmlspecialchars_array_modify (&$arr){
array_walk_recursive($arr,function(&$value){
$value=htmlspecialchars($value);
});
return $arr;
}
// this will alter the source
// 这将改变源

