wp_convert_hr_to_bytes()
云策文档标注
概述
wp_convert_hr_to_bytes() 是一个 WordPress 函数,用于将简写字节值(如 '1G'、'2M')转换为整数字节值。它处理 PHP ini 中的字节表示,支持 G、M、K 后缀,并考虑 PHP 整数最大值限制。
关键要点
- 参数:接受一个字符串 $value,可以是简写(如 '1G')或普通字节值(如 '1073741824')。
- 返回值:返回一个整数字节值,使用 min() 函数确保不超过 PHP_INT_MAX。
- 功能:通过 str_contains() 检测后缀,并乘以预定义常量(GB_IN_BYTES、MB_IN_BYTES、KB_IN_BYTES)进行转换。
- 相关函数:与 size_format() 功能相反,后者将字节转换为人类可读格式。
- 变更历史:从 4.6.0 版本从 media.php 移至 load.php,最初在 2.3.0 版本引入。
代码示例
function wp_convert_hr_to_bytes( $value ) {
$value = strtolower( trim( $value ) );
$bytes = (int) $value;
if ( str_contains( $value, 'g' ) ) {
$bytes *= GB_IN_BYTES;
} elseif ( str_contains( $value, 'm' ) ) {
$bytes *= MB_IN_BYTES;
} elseif ( str_contains( $value, 'k' ) ) {
$bytes *= KB_IN_BYTES;
}
// Deal with large (float) values which run into the maximum integer size.
return min( $bytes, PHP_INT_MAX );
}注意事项
- 函数依赖于 WordPress 定义的常量(如 GB_IN_BYTES),确保在调用前这些常量已定义。
- 输入值应经过 trim() 和 strtolower() 处理,以避免大小写和空格问题。
- 使用 min() 防止大数值溢出,确保返回有效的整数。
- 与 size_format() 配合使用,可实现字节与人类可读格式的双向转换。
原文内容
Converts a shorthand byte value to an integer byte value.
Parameters
$valuestringrequired-
A (PHP ini) byte value, either shorthand or ordinary.
Source
function wp_convert_hr_to_bytes( $value ) {
$value = strtolower( trim( $value ) );
$bytes = (int) $value;
if ( str_contains( $value, 'g' ) ) {
$bytes *= GB_IN_BYTES;
} elseif ( str_contains( $value, 'm' ) ) {
$bytes *= MB_IN_BYTES;
} elseif ( str_contains( $value, 'k' ) ) {
$bytes *= KB_IN_BYTES;
}
// Deal with large (float) values which run into the maximum integer size.
return min( $bytes, PHP_INT_MAX );
}
Skip to note 2 content
wbeaumo
Use size_format() to do the opposite (i.e., convert bytes to human-readable format).
$hr_bytes = size_format( 1024 ); // Returns '1 KiB'