is_serialized_string()
Checks if a string is serialized in the specified serialized string. That is, whether the string (and not an array or number) was serialized.
Do not confuse this function with the similar is_serialized(), which checks if the passed string is any serialized data. This function checks that it is specifically a string that is serialized.
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.
Returns
true|false.
false- this is not a serialized string.true- this is serialized data and it contains a string.
Usage
is_serialized_string( $data );
- $data(string) (required)
- Serialized data.
Examples
#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 #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. |
is_serialized_string() is serialized string code WP 7.0
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 ( ! str_ends_with( $data, ';' ) ) {
return false;
} elseif ( 's' !== $data[0] ) {
return false;
} elseif ( '"' !== substr( $data, -2, 1 ) ) {
return false;
} else {
return true;
}
}