在数据存储时,有时需要对字符串进行转义。
比如我现在用的编辑器,存储时就会以html字符串形式保存文章。
对html的字符串进行 转义的方法:
htmllentities($str), 反转义方法html_entity_decode($str);
$str = "";
var_dump($str);//string ''
$new =htmlentities($str) ;
var_dump($new);//string '<img src='http://xxx.com/xxx.jpg'>'
$back = html_entity_decode($new) ;
var_dump($back);//string ''
以上是一种简单的转义
还有一种转义方法。addslashes().
在php中如果magic_quotes_gpc的状态是打开的话,会自动对post,get,cookie过来的数据增加转义字符'\',
以保证数据不对程序和数据库产生影响。在php5.4中已移除这方法,所以始终返回false。
若magic_quotes_gpc关闭,可以手动使用addslashes()方法进行转义。stripcslashes()反转义
if(!get_magic_quotes_gpc()){//get_magic_quotes_gpc()判断是否开启magic_quotes_gpc,开则返回1,关则0
$str = "";
$new = addslashes($str);
var_dump($new);//string ''
$back = stripcslashes($new);
var_dump($back);//string ''
}
若magic_quotes_gpc打开,则相当于自动对post,get,cookie过来的数据执行addslashes(),这时在显示数据时就需要自己反转义了:
if(get_magic_quotes_gpc()){
$back = stripcslashes($str);
var_dump($back);
}