How do I correctly serialize and unserialize a string containing escaped characters?
Given:
$data = "\'test\'";
$out= serialize($data);
print_r($out); // -> s:8:"\'test\'";
The problem here is, that the string length is not accepted by unserialize:
$out = 's:8:"\'test\'"';
var_dump(unserialize($out)); // -> bool(false)
But if I change the string length to 6 (ignoring the escape chars):
$out = 's:6:"\'test\'"';
var_dump(unserialize($out)); // -> string(6) "'test'"
It unserializes correctly.
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.
is different from
if you do
it will work.