Ever wonder how to appropriately test if a string is a serialized representation of data in PHP? Well it is actually quite simple just required a little bit of testing. However, I personally did not write the function available below but I did modify it. The IsSerialized function below was taken and modified based on the one available within the code base of WordPress.

function IsSerialized($data)
{
    if( !is_string($data) )
    {
        return false;
    }

    $data = trim($data);
    if( 'N;' == $data )
    {
        return true;
    }

    $matches = array();
    if( preg_match('/^([[aCdObis]):/', $data, $matches) )
    {
        switch( $matches[1] )
        {
            case 'a': case 'C': case 'O': case 's':
                if( preg_match("/^{$matches[1]}:[0-9]+:.*[;}]$/s", $data) )
                {
                    return true;
                }
                break;

            case 'b': case 'i': case 'd':
                if( preg_match("/^{$matches[1]}:[0-9.E-]+;$/", $data) )
                {
                    return true;
                }
                break;
        }
    }

    return false;
}

So, let’s look take a look at what I modified. On line 15 and 19 I have added the C flag. But why have I done this? Well, since PHP 5 release and the availability of the Serializable interface, when a class implements this interface and an instance of the class is serialized a C is used instead of a O for identifying that this string is a representation of a serialized object.

Anyways, I hope that this function is able to be used by others as it has been a great asset within my toolkit for development. I also look forward to seeing how long WordPress takes to implement this modification – if ever.