Unserialize strings with special characters in PHP

After several hours having problems with serialized object with spanish texts in it, finally this function I found in magp.ie worked like a charm:

function mb_unserialize($string) {
    $string = preg_replace_callback(
        '!s:(\d+):"(.*?)";!s',
        function ($matches) {
            if ( isset( $matches[2] ) )
                return 's:'.strlen($matches[2]).':"'.$matches[2].'";';
        },
        $string
    );
    return unserialize($string);
}

For example:

var_dump(mb_unserialize('O:8:"stdClass":1:{s:4:"text";s:12:"áéíóúñ";}'));

class stdClass#1 (1) {
  public $text =>
  string(12) "áéíóúñ"
}

php

You might also like

Translate Symfony TimezoneType Field Type
The TimezoneType Field Type Symfony has an specific Field Type to create a Timezone select widget in...

Sort an array of objects in PHP by field
function cmp($a, $b) { return strcmp($a->name, $b->name); }usort($your_data, "cmp");Or...

Symfony Forms and Bootstrap Datetimepicker
In this example I'm going to use the spanish locale and the "Europe/Madrid" timezone.First we need...

Expose config.yml values globally for Twig templates in Symfony2 applications
Lets suppose you have created a bundle that has some specific configuration in the config.yml file (this...

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.