sanitize_locale_name()
Removes all characters that are not allowed in the locale name.
Removes everything from the string except: A-Z, a-z, 0-9, _ and -.
The function is similar to sanitize_key(), but does not change the case (uppercase letters remain as is).
Hooks from the function
Returns
String. Cleaned string.
Usage
sanitize_locale_name( $locale_name );
- $locale_name(string) (required)
- The string that will be used as the locale name.
Examples
#1 Difference between sanitize_key() and sanitize_locale_name()
The sanitize_key() function first brings the string to lower case and then cleans it, so the capital letters used in locale names are "lost".
$str = 'en_CA';
// strtolower() + cleanup '/[^a-z0-9_\-]/'
echo sanitize_key( $str ); //> en_ca ("broken" locale name)
// Cleanup only '/[^A-Za-z0-9_-]/'
echo sanitize_locale_name( $str ); //> en_CA (correct locale name) #2 Example of getting a locale via $_GET/$_COOKIE and clearing it
Part of the code for the determine_locale() function.
$wp_lang = '';
if ( ! empty( $_GET['wp_lang'] ) ) {
$wp_lang = sanitize_locale_name( wp_unslash( $_GET['wp_lang'] ) );
} elseif ( ! empty( $_COOKIE['wp_lang'] ) ) {
$wp_lang = sanitize_locale_name( wp_unslash( $_COOKIE['wp_lang'] ) );
}
Changelog
| Since 6.2.1 | Introduced. |
sanitize_locale_name() sanitize locale name code WP 7.0
function sanitize_locale_name( $locale_name ) {
// Limit to A-Z, a-z, 0-9, '_', '-'.
$sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $locale_name );
/**
* Filters a sanitized locale name string.
*
* @since 6.2.1
*
* @param string $sanitized The sanitized locale name.
* @param string $locale_name The locale name before sanitization.
*/
return apply_filters( 'sanitize_locale_name', $sanitized, $locale_name );
}