函数文档

wp_exif_frac2dec()

💡 云策文档标注

概述

wp_exif_frac2dec() 函数用于将分数字符串转换为十进制数值。它处理输入验证,确保字符串格式正确,并返回计算结果或0。

关键要点

  • 函数接受一个分数字符串参数,返回整数或浮点数。
  • 输入验证包括检查是否为标量、字符串格式、分数分隔符数量以及分子分母是否为数字。
  • 无效输入(如非标量、布尔值、非数字分子分母或分母为零)会返回0。
  • 如果字符串是数字但非分数格式,则直接转换为浮点数。

代码示例

function wp_exif_frac2dec( $str ) {
    if ( ! is_scalar( $str ) || is_bool( $str ) ) {
        return 0;
    }

    if ( ! is_string( $str ) ) {
        return $str; // This can only be an integer or float, so this is fine.
    }

    // Fractions passed as a string must contain a single `/`.
    if ( substr_count( $str, '/' ) !== 1 ) {
        if ( is_numeric( $str ) ) {
            return (float) $str;
        }

        return 0;
    }

    list( $numerator, $denominator ) = explode( '/', $str );

    // Both the numerator and the denominator must be numbers.
    if ( ! is_numeric( $numerator ) || ! is_numeric( $denominator ) ) {
        return 0;
    }

    // The denominator must not be zero.
    if ( 0 == $denominator ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- Deliberate loose comparison.
        return 0;
    }

    return $numerator / $denominator;
}

注意事项

  • 函数使用宽松比较检查分母是否为零,以避免严格比较可能带来的问题。
  • 该函数主要用于图像元数据处理,如 wp_read_image_metadata() 中。
  • 自 WordPress 2.5.0 版本引入。

📄 原文内容

Converts a fraction string to a decimal.

Parameters

$strstringrequired
Fraction string.

Return

int|float Returns calculated fraction or integer 0 on invalid input.

Source

function wp_exif_frac2dec( $str ) {
	if ( ! is_scalar( $str ) || is_bool( $str ) ) {
		return 0;
	}

	if ( ! is_string( $str ) ) {
		return $str; // This can only be an integer or float, so this is fine.
	}

	// Fractions passed as a string must contain a single `/`.
	if ( substr_count( $str, '/' ) !== 1 ) {
		if ( is_numeric( $str ) ) {
			return (float) $str;
		}

		return 0;
	}

	list( $numerator, $denominator ) = explode( '/', $str );

	// Both the numerator and the denominator must be numbers.
	if ( ! is_numeric( $numerator ) || ! is_numeric( $denominator ) ) {
		return 0;
	}

	// The denominator must not be zero.
	if ( 0 == $denominator ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- Deliberate loose comparison.
		return 0;
	}

	return $numerator / $denominator;
}

Changelog

Version Description
2.5.0 Introduced.