教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 php中序列化与反序列化在utf8和gbk编码中测试

php中序列化与反序列化在utf8和gbk编码中测试

发布时间:2016-10-23   编辑:jiaochengji.com
教程集为您提供php中序列化与反序列化在utf8和gbk编码中测试等资源,欢迎您收藏本站,我们将为您提供最新的php中序列化与反序列化在utf8和gbk编码中测试资源
在php中如果我们统一编码是没有什么问题了,但是很多朋友会发现一个问题就是utf8和gbk编码中返回的值会有所区别了,下面一聚教程小编就来介绍它们的一些问题。

php 在utf8和gbk编码下使用serialize和unserialize互相序列化和反序列化会出现无法成功反序列化的问题。
问题出现的原因主要是在不同编码下strlen函数计算中文字符串长度不同的原因。

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy6535')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy6535><?php
$array=array('title'=>'php教程分享网','url'=>'http://www.jiaochengji.com');
echo serialize($array);
//gbk编码  a:2:{s:5:"title";s:13:"php教程分享网";s:3:"url";s:20:"http://www.jiaochengji.com";}
//utf8编码 a:2:{s:5:"title";s:18:"php教程分享网";s:3:"url";s:20:"http://www.jiaochengji.com";}
?>

要解决这个问题就要在反序列化的时候重新修正字符串的长度。
解决方案

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy5091')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy5091>

<?php

$str='a:2:{s:5:"title";s:13:"php教程分享网";s:3:"url";s:20:"http://www.jiaochengji.com";}';
$regex = '/s\:(\d )\:\"([^\"] )\"/isx';

$str = preg_replace_callback(

$regex ,

"fixser",

$str);

function fixser($matches)

{

 return 's:'.strlen($matches[2]).':'.'"'.$matches[2].'"';

}

?>

 
可以改成匿名函数

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy2995')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy2995>

<?php
$str='a:2:{s:5:"title";s:13:"php教程分享网";s:3:"url";s:20:"http://www.jiaochengji.com";}';
$regex = '/s\:(\d )\:\"([^\"] )\"/isx';

$str = preg_replace_callback(
$regex ,
function ($matches)
{
 return 's:'.strlen($matches[2]).':'.'"'.$matches[2].'"';
},
$str);

?>

您可能感兴趣的文章:
php中序列化与反序列化在utf8和gbk编码中测试
php数组编码转换小例子
php数组编码转换的方法参考
php编码转换函数mb_convert_encoding与iconv
php编码转换函数mb_convert_encoding与iconv使用说明
mysql中文乱码解决方法汇总
php提示Notice:unserialize()[function.unserialize]:Error错误解决办法
(图文)mysql字符集设置详解
查询mysql编码以及解决mysql乱码问题
PHP序列化和反序列化语法差异问题

[关闭]
~ ~