函数文档

is_serialized()

💡 云策文档标注

概述

is_serialized() 函数用于检查一个值是否已被序列化。它接受一个参数 $data,如果 $data 不是字符串,则始终返回 false,因为序列化数据总是字符串格式。

关键要点

  • 函数用于检测值是否被序列化,返回布尔值(true 表示已序列化,false 表示未序列化)。
  • 参数 $data 是必需的字符串值,用于检查;$strict 是可选的布尔参数,控制是否严格检查字符串结尾,默认值为 true。
  • 如果 $data 不是字符串,函数直接返回 false,无需进一步处理。
  • 序列化数据通常用于在数据库中存储和检索 PHP 可理解的数据格式。
  • 相关函数包括 maybe_serialize() 和 maybe_unserialize(),用于在需要时序列化或反序列化数据。

代码示例

is_serialized( $data );

注意事项

数据可能需要序列化才能成功存储到数据库并从数据库中检索,以便 PHP 能够理解其格式。


📄 原文内容

Checks value to find if it was serialized.

Description

If $data is not a string, then returned value will always be false.
Serialized data is always a string.

Parameters

$datastringrequired
Value to check to see if was serialized.
$strictbooloptional
Whether to be strict about the end of the string.

Default:true

Return

bool False if not serialized and true if it was.

More Information

Usage:
is_serialized( $data );
Notes:

Data might need to be serialized to allow it to be successfully stored and retrieved from a database in a form that PHP can understand.

Source

function is_serialized( $data, $strict = true ) {
	// If it isn't a string, it isn't serialized.
	if ( ! is_string( $data ) ) {
		return false;
	}
	$data = trim( $data );
	if ( 'N;' === $data ) {
		return true;
	}
	if ( strlen( $data ) < 4 ) {
		return false;
	}
	if ( ':' !== $data[1] ) {
		return false;
	}
	if ( $strict ) {
		$lastc = substr( $data, -1 );
		if ( ';' !== $lastc && '}' !== $lastc ) {
			return false;
		}
	} else {
		$semicolon = strpos( $data, ';' );
		$brace     = strpos( $data, '}' );
		// Either ; or } must exist.
		if ( false === $semicolon && false === $brace ) {
			return false;
		}
		// But neither must be in the first X characters.
		if ( false !== $semicolon && $semicolon < 3 ) {
			return false;
		}
		if ( false !== $brace && $brace < 4 ) {
			return false;
		}
	}
	$token = $data[0];
	switch ( $token ) {
		case 's':
			if ( $strict ) {
				if ( '"' !== substr( $data, -2, 1 ) ) {
					return false;
				}
			} elseif ( ! str_contains( $data, '"' ) ) {
				return false;
			}
			// Or else fall through.
		case 'a':
		case 'O':
		case 'E':
			return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
		case 'b':
		case 'i':
		case 'd':
			$end = $strict ? '$' : '';
			return (bool) preg_match( "/^{$token}:[0-9.E+-]+;$end/", $data );
	}
	return false;
}

Changelog

Version Description
6.1.0 Added Enum support.
2.0.5 Introduced.

User Contributed Notes