'ec"','two'=>5));function&"/> 'ec"','two'=>5));function&">

用递归addslashes函数转义数组解决方案

WBOY
Release: 2016-06-13 12:02:15
Original
922 people have browsed it

用递归addslashes函数转义数组
有个一个数组,可能是多维的,里面有些值带有特殊符号 比如“  我用递归加addslashes()转义  

没有达到效果 帮忙看看哪错了
$arr=array('ii"',array('one'=>'ec"','two'=>5));
function t(&$arr){
foreach($arr as $v){
if(is_string($v)){
$arr[]=addslashes($v);
}else{
t($v);
}
}
}
t($arr);
echo "

";<br>print_r($arr);<br>echo '
Copy after login
';



前台页面是这么输出的
________________________________________________________

Warning: Invalid argument supplied for foreach() in D:\AppServ\www\index.php on line 22
Array
(
    [0] => ii"
    [1] => Array
        (
            [one] => ec"
            [two] => 5
        )

    [2] => ii\"
    [3] => ii\\\"
)

------解决方案--------------------
你自己对比下
$arr=array('ii"',array('one'=>'ec"','two'=>5),'aa"a');<br />function t(& $arr){<br />    foreach($arr as $k => $v){<br />        if(is_string($v)){<br />            $arr[$k] = addslashes($v);<br />        }else{<br />            $arr[$k] = t($v);<br />        }<br />    }<br />    return $arr;<br />}<br />t($arr);<br />echo "<pre class="brush:php;toolbar:false">";<br />print_r($arr);<br />echo '
Copy after login
';
------解决方案--------------------
$arr = array('ii"',array('one'=>"ec'",'two'=>5));<br />array_walk_recursive($arr, function(&$v) { $v = addslashes($v);} );<br />print_r($arr);<br />
Copy after login
Array<br />(<br />    [0] => ii\"<br />    [1] => Array<br />        (<br />            [one] => ec\'<br />            [two] => 5<br />        )<br /><br />)<br /><br />
Copy after login

------解决方案--------------------
改成這樣就可以了。
<br />function t(&$arr){<br />	foreach($arr as $key=>$v){<br />		if(is_string($v)){<br />			$arr[$key]=addslashes($v);<br />		}else{<br />			t($arr[$key]);<br />		}<br />	}<br />}<br />
Copy after login

------解决方案--------------------
再改一下。

<br />function t(&$arr){<br />    foreach($arr as $key=>$v){<br />        if(is_array($v)){<br />            t($arr[$key]);<br />        }else{<br />            $arr[$key]=addslashes($v);<br />		}<br />    }<br />}<br /> <br />$arr=array('ii"',array('one'=>'ec"','two'=>'5'));<br />t($arr);<br /><br />print_r($arr);<br />
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!