2 个相同的字符串,一个在反序列化时出错,另一个则不然. 为什么


2 identical strings, one gives error when unserializing, the other doesn't. Why?

这是代码:

<?php
$txt = 'a:1:{s:14:"exclude_stores";a:3:{i:0;s:7:"phoenix";i:1;s:8:"chandler";i:2;s:6:"tucson";}}' //serialized PHP array
$str = htmlspecialchars(urldecode($txt));
$str = preg_replace('/'&lt;'?.*'?'&gt;/ims', '', $str); //get rid of php tags/code enclosed in <? ... >
$str = preg_replace('/'&gt;/ims', '>', $str); //change &gt; back to >
?>

此时,如果我这样做:

<?php
echo gettype($txt) . ' ' . $txt . '<br>';
echo gettype($str) . ' ' . $str;
?>

我得到:

string a:1:{s:14:"exclude_stores";a:3:{i:0;s:7:"phoenix";i:1;s:8:"chandler";i:2;s:6:"tucson";}}
string a:1:{s:14:"exclude_stores";a:3:{i:0;s:7:"phoenix";i:1;s:8:"chandler";i:2;s:6:"tucson";}}

字符串看起来完全相同。然后,如果我这样做:

<?php
$u1 = unserialize($txt);
print_r($u1);
$u2 = unserialize($str);
print_r($u2);
?>

我得到: 数组 ( [exclude_stores] => 数组 ( [0] => 凤凰 [1] => 钱德勒 [2] => 图森 ) )

Notice: unserialize(): Error at offset 5 of 128 bytes in ...

反序列化不喜欢$str发生了一些事情,但我无法弄清楚它是什么。在屏幕上,字符串看起来完全相同,当我将它们粘贴到 N++ 中时,它们看起来完全相同。

我怀疑htmlspecialchars,urldecode或preg_replace正在对我看不到的文本做一些事情。任何帮助,不胜感激。

字符串不同,但它们在屏幕上显示相同,因为 htmlspecialchars 正在转换为在浏览器屏幕上呈现为 " 符号的 &quot;

尝试从 CLI 运行脚本以了解我的意思

$str等于:

string a:1:{s:14:&quot;exclude_stores&quot;;a:3:{i:0;s:7:&quot;phoenix&quot;;i:1;s:8:&quot;chandler&quot;;i:2;s:6:&quot;tucson&quot;;}}

您可以了解为什么它不会反序列化:)