函数文档

wp_is_json_media_type()

💡 云策文档标注

概述

wp_is_json_media_type() 函数用于检查字符串是否为有效的 JSON Media Type。它通过正则表达式匹配实现,并包含缓存机制以提高性能。

关键要点

  • 函数接受一个必需的字符串参数 $media_type,返回布尔值表示是否为有效 JSON Media Type。
  • 内部使用静态缓存数组 $cache 来存储已检查的结果,避免重复计算。
  • 正则表达式匹配模式为 '/(^|s|,)application/([w!#$&-^.+]++)?json(+oembed)?($|s|;|,)/i',支持多种 JSON 变体。
  • 该函数自 WordPress 5.6.0 版本引入。

代码示例

function wp_is_json_media_type( $media_type ) {
    static $cache = array();

    if ( ! isset( $cache[ $media_type ] ) ) {
        $cache[ $media_type ] = (bool) preg_match( '/(^|s|,)application/([w!#$&-^.+]++)?json(+oembed)?($|s|;|,)/i', $media_type );
    }

    return $cache[ $media_type ];
}

注意事项

  • 函数区分大小写,正则表达式使用 'i' 修饰符进行不区分大小写匹配。
  • 缓存机制仅在同一请求内有效,跨请求不会保留。
  • 相关函数包括 WP_REST_Request::is_json_content_type() 和 wp_is_json_request(),用于检查 JSON Content-Type 和 JSON 请求。

📄 原文内容

Checks whether a string is a valid JSON Media Type.

Parameters

$media_typestringrequired
A Media Type string to check.

Return

bool True if string is a valid JSON Media Type.

Source

function wp_is_json_media_type( $media_type ) {
	static $cache = array();

	if ( ! isset( $cache[ $media_type ] ) ) {
		$cache[ $media_type ] = (bool) preg_match( '/(^|s|,)application/([w!#$&-^.+]++)?json(+oembed)?($|s|;|,)/i', $media_type );
	}

	return $cache[ $media_type ];
}

Changelog

Version Description
5.6.0 Introduced.