is_serialized_string()WP 2.0.5

Check whether serialized data is of string type.

1 time — 0.000039 sec (very fast) | 50000 times — 0.03 sec (speed of light) | PHP 7.0.8, WP 4.6.1

No Hooks.

Return

true|false. False if not a serialized string, true if it is.

Usage

is_serialized_string( $data );
$data(string) (required)
Serialized data.

Examples

0

#1 Demonstration of serialized string checking.

// serialized array
is_serialized_string( 'a:1:{s:3:"foo";s:3:"bar";}' ); //> false

// serialized string - serialize( 'foo' )
is_serialized_string( 's:3:"foo";' ); //> true
0

#2 This function is commonly used in conjunction with is_serialized()

Let's say $option could have serialized data and all kinds of arrays, boolean numbers, etc.

// If this is serialized data
if ( is_serialized( $option ) ) {

	// if there is only a string in the serial data
	if ( is_serialized_string( $option ) ) {
		echo esc_html( unserialize( $option ) );
	}
	// the serialized data contains something other than a string
	else {
		echo 'SERIALIZED DATA';
	}
}

See also: is_serialized().

Changelog

Since 2.0.5 Introduced.

Code of is_serialized_string() WP 5.9.3

function is_serialized_string( $data ) {
	// if it isn't a string, it isn't a serialized string.
	if ( ! is_string( $data ) ) {
		return false;
	}
	$data = trim( $data );
	if ( strlen( $data ) < 4 ) {
		return false;
	} elseif ( ':' !== $data[1] ) {
		return false;
	} elseif ( ';' !== substr( $data, -1 ) ) {
		return false;
	} elseif ( 's' !== $data[0] ) {
		return false;
	} elseif ( '"' !== substr( $data, -2, 1 ) ) {
		return false;
	} else {
		return true;
	}
}