This problem is a classic case of someone trying to perform a shortcut when updating a value in a serialized string. The lesson swiftly learned to avoid this headache is to unserialize your data, modify your value(s), then re-serialize it.
I feel regular expressions afford a more direct approach for trying to parse the corrupted serialized string. To be perfectly clear, my snippet will only update the byte/character counts; if you have a serialized string that is corrupted by some other means, this will not be the remedy.
Here is a simple preg_replace_callback()
call that only captures the value substring and unconditionally replaces all byte counts in the serialized string:
Code: (Demo)
$corrupted_byte_counts = <<<STRING
a:1:{i:0;a:3:{s:7:"address";s:52:"Elågåresgude 41, 2200 Københamm N";s:12:"company_name";s:14:"Kaffe og Kluns";s:9:"telephone";s:0:"";}}
STRING;
$repaired = preg_replace_callback(
'/s:\d+:"(.*?)";/s',
function ($m) {
return 's:' . strlen($m[1]) . ":\"{$m[1]}\";";
},
$corrupted_byte_counts
);
echo "corrupted serialized array:\n$corrupted_byte_counts";
echo "\n---\n";
echo "repaired serialized array:\n$repaired";
echo "\n---\n";
print_r(unserialize($repaired));
Output:
corrupted serialized array:
a:1:{i:0;a:3:{s:7:"address";s:52:"Elågåresgude 41, 2200 Københamm N";s:12:"company_name";s:14:"Kaffe og Kluns";s:9:"telephone";s:0:"";}}
---
repaired serialized array:
a:1:{i:0;a:3:{s:7:"address";s:36:"Elågåresgude 41, 2200 Københamm N";s:12:"company_name";s:14:"Kaffe og Kluns";s:9:"telephone";s:0:"";}}
---
Array
(
[0] => Array
(
[address] => Elågåresgude 41, 2200 Københamm N
[company_name] => Kaffe og Kluns
[telephone] =>
)
)
I've even gone a bit further to address a possible fringe case. Without implementing the pattern extension in that link, the above snippet will work as desired on strings with:
- multibyte characters
- newlines
- colons
- semicolons
- commas
- single quotes
- double quotes
It only breaks when a string to be matched contains ";
-- in which case, my above link attempts to address that possibility.