wppaste
WordPress

sanitize_key( string $key ): string

Since
3.0.0
Source
wp-includes/formatting.php:2170

Strips a string down to lowercase letters, numbers, dashes and underscores so it can be safely used as an internal identifier like a meta key, option name or transient name. Non-scalar input (arrays, objects) is silently converted to an empty string rather than raising an error. Pass the result through the sanitize_key filter if a plugin needs to adjust generated keys globally.

Sanitizes a string key.

Description

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

Compatibility

WordPress
since 3.0.0
PHP
7.4–8.6-dev
  • 6.7.7
  • 6.8.8
  • 6.9.7
  • 7.0.4
  • 7.1.0

Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.

Parameters

$keystring
String key.

Return value

string
Sanitized key.

Code examples

Every example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.

Building a safe meta key from user-supplied input before calling get_post_meta

A form field or query var might arrive with stray casing or whitespace, so run it through sanitize_key() before using it as a meta key lookup.

$user_supplied = ' Price ';
$meta_key      = sanitize_key( $user_supplied );
$price         = get_post_meta( 2, $meta_key, true );

printf( 'Sanitized key: %s | Value: %s', esc_html( $meta_key ), esc_html( $price ) );

The trailing/leading space and mixed case are stripped, so ' Price ' becomes 'price' and matches the existing post meta on post 2.

Turning a category name into a safe PHP array key

Category names can contain spaces or punctuation that make poor array keys, so sanitize each one before grouping term IDs by name.

$categories = get_categories( array( 'hide_empty' => false ) );
$grouped    = array();

foreach ( $categories as $category ) {
	$key             = sanitize_key( $category->name );
	$grouped[ $key ] = $category->term_id;
}

print_r( $grouped );

Common problems and fixes · 3

Why does sanitize_key() return an empty string for my value?

The function only processes scalar values (is_scalar()). If you pass an array, object, or null, the sanitized key is set to an empty string before the filter even runs. - Cast or extract a string before calling it, e.g. sanitize_key( (string) $value ). - Check is_scalar( $value ) yourself first if the input source is unpredictable.

Why did my uppercase letters and spaces disappear from the key?

sanitize_key() lowercases the string with strtolower() and then removes every character that is not a-z, 0-9, a dash, or an underscore with a regex, so spaces, uppercase letters, and punctuation are all stripped, not converted. - If you need spaces turned into dashes for a URL slug, use sanitize_title() instead. - If you need to keep uppercase for display, sanitize a copy and keep the original separately.

Can a plugin change the value sanitize_key() returns?

Yes. The function passes its result through apply_filters( 'sanitize_key', $sanitized_key, $key' ) before returning it, so any plugin hooked to that filter can further alter or replace the value. - Disable other plugins temporarily to rule out interference if a key looks unexpectedly modified. - Search the codebase for add_filter( 'sanitize_key' to find the offending callback.

Alternatives and related functions

sanitize_title
When the string is meant to become a URL slug and you want spaces converted to dashes rather than removed.
sanitize_html_class
When the sanitized value will be output as an HTML class attribute rather than used as an internal array or meta key.
sanitize_text_field
When you are cleaning general free-text user input, not a fixed-format identifier like a key or slug.
sanitize_file_name
When the string will be used as a filename rather than a database or array key.

Performance profile

How much work a call to sanitize_key() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.

Cost class
Trivial

Touches nothing outside its own arguments.

Scaling
Constant

No loop in the body: the same number of instructions runs whatever you pass in.

Instructions
10–17

Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 17.

Plugin surface
1 hook

Third-party callbacks on 'sanitize_key' run inside this call, and their cost is not bounded by anything here.

Called by
50

50 places in core call this, so the cost is paid more often than your own code shows.

What it touches

  • hookthird-party callbacksapply_filters()called directly

What one call costs · 2 distinct outcomes

One number would be a lie: the work depends on which branch runs. These are every distinct cost sanitize_key() can have, taken from its control-flow graph on PHP 8.5.

WhenInstructionsCalls it makes
!is_scalar($key)10apply_filters()
is_scalar($key)17strtolower(), apply_filters()

Across PHP versions

PHPCompiledExecutedBranchesNotes
8.6-dev1710–171
8.51710–171
8.41710–1713 fewer instructions than PHP 8.3
8.32010–201
8.22010–201
8.12010–2012 fewer instructions than PHP 7.4
7.42212–221

An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.

Hooks and filters fired · 1

One hook fires while sanitize_key() runs, in this order:

  1. apply_filters( sanitize_key )filterline 2186 (+16 into the body)

    Filters a sanitized key string.

Uses · 1

  • apply_filters()Calls the callback functions that have been added to a filter hook.

Used by · 50

Show all 50

Source code

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 );}

Changelog

Introduced in 3.0.0. Unchanged from 6.7.7 through 7.1.0.

  1. 6.7.7
  2. 6.8.8
  3. 6.9.7
  4. 7.0.4
  5. 7.1.0

Signature, return type and hooks compared across 5 parsed releases.

About this page

Parsed data
Generated from the wordpress-develop 6.7.7 tag, from src/wp-includes/formatting.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.
Corrections
Something wrong on this page? Report it and it gets fixed in the next regeneration.