函数文档

wp_is_uuid()

💡 云策文档标注

概述

wp_is_uuid() 函数用于验证 UUID 字符串的有效性。它接受 UUID 字符串和可选的版本参数,通过正则表达式匹配来返回布尔值结果。

关键要点

  • 函数接受两个参数:$uuid(必需,要检查的 UUID)和 $version(可选,指定 UUID 版本,目前仅支持版本 4)。
  • 如果 $uuid 不是字符串,函数直接返回 false。
  • 当指定 $version 为 4 时,使用 V4 正则表达式;否则使用通用正则表达式。
  • 返回值:true 表示 UUID 有效,false 表示无效。

代码示例

function wp_is_uuid( $uuid, $version = null ) {

	if ( ! is_string( $uuid ) ) {
		return false;
	}

	if ( is_numeric( $version ) ) {
		if ( 4 !== (int) $version ) {
			_doing_it_wrong( __FUNCTION__, __( 'Only UUID V4 is supported at this time.' ), '4.9.0' );
			return false;
		}
		$regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/';
	} else {
		$regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/';
	}

	return (bool) preg_match( $regex, $uuid );
}

注意事项

  • 如果 $version 参数被指定为非 4 的值,函数会调用 _doing_it_wrong() 并返回 false,因为目前仅支持 UUID V4。
  • 函数在 WordPress 4.9.0 版本中引入。

📄 原文内容

Validates that a UUID is valid.

Parameters

$uuidmixedrequired
UUID to check.
$versionintoptional
Specify which version of UUID to check against. Default is none, to accept any UUID version. Otherwise, only version allowed is 4.

Default:null

Return

bool The string is a valid UUID or false on failure.

Source

function wp_is_uuid( $uuid, $version = null ) {

	if ( ! is_string( $uuid ) ) {
		return false;
	}

	if ( is_numeric( $version ) ) {
		if ( 4 !== (int) $version ) {
			_doing_it_wrong( __FUNCTION__, __( 'Only UUID V4 is supported at this time.' ), '4.9.0' );
			return false;
		}
		$regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/';
	} else {
		$regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/';
	}

	return (bool) preg_match( $regex, $uuid );
}

Changelog

Version Description
4.9.0 Introduced.