php中序列化与反序列化在utf8和gbk编码中测试
在php中如果我们统一编码是没有什么问题了,但是很多朋友会发现一个问题就是utf8和gbk编码中返回的值会有所区别了,下面php入门网小编就来介绍它们的一些问题.
php 在utf8和gbk编码下使用serialize和unserialize互相序列化和反序列化会出现无法成功反序列化的问题,问题出现的原因主要是在不同编码下strlen函数计算中文字符串长度不同的原因,代码如下:
<?php
$array=array('title'=>'php入门','url'=>'http://www.phprm.com');
echo serialize($array);
//gbk编码 a:2:{s:5:"title";s:13:"php入门";s:3:"url";s:20:"http://www.phprm.com";}
//utf8编码 a:2:{s:5:"title";s:18:"php入门";s:3:"url";s:20:"http://www.phprm.com";}
要解决这个问题就要在反序列化的时候重新修正字符串的长度,解决方案代码如下:
<?php
$str='a:2:{s:5:"title";s:13:"php入门";s:3:"url";s:20:"http://www.phprm.com";}';
$regex = '/s\:(\d+)\:\"([^\"]+)\"/isx';
$str = preg_replace_callback(
$regex ,
"fixser",
$str);
function fixser($matches)
{
return 's:'.strlen($matches[2]).':'.'"'.$matches[2].'"';
}可以改成匿名函数,代码如下:
<?php
$str='a:2:{s:5:"title";s:13:"php入门";s:3:"url";s:20:"http://www.phprm.com";}';
$regex = '/s\:(\d+)\:\"([^\"]+)\"/isx';
$str = preg_replace_callback(
$regex ,
function ($matches)
{
return 's:'.strlen($matches[2]).':'.'"'.$matches[2].'"';
},
$str);本文地址:http://www.phprm.com/develop/fs9200.html
转载随意,但请附上文章地址:-)