I need to stripslashes
all items of an array at once.
Any idea how can I do this?
foreach ($your_array as $key=>$value) {
$your_array[$key] = stripslashes($value);
}
or for many levels array use this :
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
print_r($array);
$result= Recursiver_of_Array($array, 'stripslashes');
code:
function Recursiver_of_Array($array,$function_name=false){
//on first run, we define the desired function name to be executed on values
if ($function_name) { $GLOBALS['current_func_name']= $function_name; } else {$function_name=$GLOBALS['current_func_name'];}
//now, if it's array, then recurse, otherwise execute function
return is_array($array) ? array_map('Recursiver_of_Array', $array) : $function_name($array);
}
I found this class / function
<?php
/**
* Remove slashes from strings, arrays and objects
*
* @param mixed input data
* @return mixed cleaned input data
*/
function stripslashesFull($input)
{
if (is_array($input)) {
$input = array_map('stripslashesFull', $input);
} elseif (is_object($input)) {
$vars = get_object_vars($input);
foreach ($vars as $k=>$v) {
$input->{$k} = stripslashesFull($v);
}
} else {
$input = stripslashes($input);
}
return $input;
}
?>
on this blog and it really helped me, and now i could pass variables, arrays and objects all through the same function...
You can use array_map:
$output = array_map('stripslashes', $array);
Parse array recursevely, with this solution you don't have to dublicate your array
function addslashes_extended(&$arr_r){
if(is_array($arr_r))
{
foreach ($arr_r as &$val){
is_array($val) ? addslashes_extended($val):$val=addslashes($val);
}
unset($val);
}
else
$arr_r=addslashes($arr_r);
return $arr_r;
}
For uni-dimensional arrays, array_map
will do:
$a = array_map('stripslashes', $a);
For multi-dimensional arrays you can do something like:
$a = json_decode(stripslashes(json_encode($a)), true);
This last one can be used to fix magic_quotes, see this comment.