sanitize_key()
Clears the string to use it as a key. Keys are used as different internal IDs.
Converts the string to lowercase (see strtolower()) and removes everything from the string except a-z0-9_-.
1 time — 0.000013 sec (very fast) | 50000 times — 0.04 sec (speed of light)
Hooks from the function
Returns
String. Cleaned key.
Usage
sanitize_key( $key );
- $key(string) (required)
- String that will be used as a key.
Examples
#1 Demo of cleaning
In code below is show how sanitize_key() clears string with uppercase & lowercase letters, numbers, dash, underscore, forward slash, brackets, spaces.
echo sanitize_key( 'Testexample1-_/[]{}' ); // testexample1-_
echo sanitize_key( ' My Key ' ); // mykey
echo sanitize_key( 'My-Key' ); // my-key
echo sanitize_key( 'My_Key' ); // my_key
So as you can see this function turn uppercase letter into lowercase, remove forward slash, spaces, brackets and any other non-standard characters.
Changelog
| Since 3.0.0 | Introduced. |
sanitize_key() sanitize key code WP 6.9.1
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 );
}