函数文档

sanitize_key()

💡 云策文档标注

概述

sanitize_key() 函数用于清理字符串键,确保其符合 WordPress 内部标识符的规范。它通过转换为小写并移除非法字符来生成安全的键值。

关键要点

  • 函数 sanitize_key() 清理字符串键,仅允许小写字母、数字、短横线和下划线。
  • 参数 $key 为必需字符串,函数返回清理后的字符串。
  • 内部实现使用 strtolower() 和 preg_replace() 进行转换和过滤。
  • 提供 'sanitize_key' 过滤器钩子,允许开发者自定义清理逻辑。
  • 广泛用于 WordPress 核心功能,如插件依赖检查、元数据处理和查询解析等。

代码示例

function sanitize_key( $key ) {
    $sanitized_key = '';

    if ( is_scalar( $key ) ) {
        $sanitized_key = strtolower( $key );
        $sanitized_key = preg_replace( '/[^a-z0-9_-]/', '', $sanitized_key );
    }

    /**
     * Filters a sanitized key string.
     *
     * @since 3.0.0
     *
     * @param string $sanitized_key Sanitized key.
     * @param string $key           The key prior to sanitization.
     */
    return apply_filters( 'sanitize_key', $sanitized_key, $key );
}

注意事项

  • 仅当 $key 为标量(如字符串)时进行清理,否则返回空字符串。
  • 清理过程会移除所有非小写字母、数字、短横线或下划线的字符,包括大写字母、斜杠和括号等。
  • 自 WordPress 3.0.0 版本引入,是核心函数,常用于确保键值的一致性和安全性。

📄 原文内容

Sanitizes a string key.

Description

Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes, and underscores are allowed.

Parameters

$keystringrequired
String key.

Return

string Sanitized key.

Source

function sanitize_key( $key ) {
	$sanitized_key = '';

	if ( is_scalar( $key ) ) {
		$sanitized_key = strtolower( $key );
		$sanitized_key = preg_replace( '/[^a-z0-9_-]/', '', $sanitized_key );
	}

	/**
	 * Filters a sanitized key string.
	 *
	 * @since 3.0.0
	 *
	 * @param string $sanitized_key Sanitized key.
	 * @param string $key           The key prior to sanitization.
	 */
	return apply_filters( 'sanitize_key', $sanitized_key, $key );
}

Hooks

apply_filters( ‘sanitize_key’, string $sanitized_key, string $key )

Filters a sanitized key string.

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes