PHP:序列化和反序列化包含转义字符的字符串 [英] PHP: serializing and unserializing string containing escaped characters

查看:572
本文介绍了PHP:序列化和反序列化包含转义字符的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何正确序列化和取消排序包含转义字符的字符串?

How do I correctly serialize and unserialize a string containing escaped characters?

给定:

$data = "\'test\'";
$out= serialize($data);
print_r($out); // ->  s:8:"\'test\'";

这里的问题是字符串长度不被unserialize接受:

The problem here is, that the string length is not accepted by unserialize:

$out = 's:8:"\'test\'"';
var_dump(unserialize($out)); // -> bool(false)

但是,如果我将字符串长度更改为6(忽略转义字符):

But if I change the string length to 6 (ignoring the escape chars):

$out = 's:6:"\'test\'"';
var_dump(unserialize($out)); // -> string(6) "'test'"

它不正确地排序。

什么是处理这个问题的好方法?

What would be a good way of handling this problem?

推荐答案

您的测试用例不匹配你在第一个例子中用双引号括起字符串,在第二个例子中用单引号将字符串包裹起来,导致转义字符在后面被字面上取代。

Your test cases don't match, you're wrapping the string in double quotes in your first example and single quotes in the second, causing the escape character to be taken literally in the latter.

$out = '\'test\'';

不同于

$data = "\'test\'";

如果你这样做

$data = "\'test\'";
$out= serialize($data);
print_r($out); // ->  s:8:"\'test\'";
$data = unserialize($out);
print_r($data); // -> \'test\'

它会工作。

这篇关于PHP:序列化和反序列化包含转义字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆