我可以通过循环运行 $_POST 数组以获得与以下代码相同的结果吗?
$_POST['manufacturer'] = strip_tags($_POST['manufacturer']);<br>
$_POST['part_no'] = strip_tags($_POST['part_no']);<br>
$_POST['product_name'] = strip_tags($_POST['product_name']);<br>
$_POST['link'] = strip_tags($_POST['link']);<br>
或者有没有办法将 strip_tags() 应用于 $_POST 数组中的每个字段?
是的,使用 array_map()
$_POST = array_map("strip_tags", $_POST);
如前所述,array_map()
是您要查找的函数
但是,请注意,如果数组值之一本身就是数组,则strip_tags将使该值无效。该键将保留在父数组中,但该键的值将为 null。这是我用来代替array_map来避免这种情况的函数。一个可能的用途是,如果你的 $_POST 中有 html 输入字段数组。例如,名称类似于 name="hello[]"
的多个输入
function strip_tags_array($array){
$result=array();
if(is_array($array)){
foreach($array as $key=>$value){
if(is_array($value)){
$result[$key]=strip_tags_array($value);
}
else if(is_string($value)){
$result[$key]=strip_tags($value);
}
else{
$result[$key]=$value;
}
}
}
return $result;
}
$_POST = strip_tags_array($_POST);
无法在我的服务器上使用任何示例。你们在测试解决方案吗?这对我有用:
// no code
$allowcode=""; // put allowed code tags here
foreach ($_POST as $key => $value) { $$key=strip_tags($value, $allowcode); }
foreach ($_GET as $key => $value) { $$key=strip_tags($value, $allowcode); }
如果你不想使用任何PHP内置函数,你可以像下面这样做:
foreach($_POST AS $key=>$val)
{
$_POST[$key] = strip_tags($val);
}