[英]Assign new value to variable if unserialize() fail
Is there a better or more robust solution to this problem than the one I have found? 是否有比我发现的更好或更强大的解决方案?
$string = "a:1:{s:19:\"is_featured_service\";b:0;}";
$unserialized_string = @unserialize($string);
if ($unserialized_string === false){
$unserialized_string = 'another value';
}
I like this because you don't have to try to supress errors: 我喜欢这个,因为您不必尝试抑制错误:
/**
* Check value to find if it is serialized data.
*
* Function borrowed from Wordpress.
*
* @param mixed $data Value to check to see if was serialized.
* @return bool False if not serialized and true if it was.
*/
function is_serialized( $data ) {
// if it isn't a string, it isn't serialized
if ( ! is_string( $data ) )
return false;
$data = trim( $data );
if ( 'N;' == $data )
return true;
$length = strlen( $data );
if ( $length < 4 )
return false;
if ( ':' !== $data[1] )
return false;
$lastc = $data[$length-1];
if ( ';' !== $lastc && '}' !== $lastc )
return false;
$token = $data[0];
switch ( $token ) {
case 's' :
if ( '"' !== $data[$length-2] )
return false;
case 'a' :
case 'O' :
return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
case 'b' :
case 'i' :
case 'd' :
return (bool) preg_match( "/^{$token}:[0-9.E-]+;\$/", $data );
}
return false;
}
$string = "a:1:{s:19:\"is_featured_service\";b:0;}";
$x = is_serialized( $string )
? unserialize( $string )
: 'Some default value';
I would only keep the @
if you dont want to deal with errors, which it seems like you do. 如果您不想处理错误,我只会保留
@
,好像您这样做一样。 Then change it into ternary to make it smaller: 然后将其更改为三元以使其更小:
$unserialized_string = @unserialize($string) ?: 'another value';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.