重写wordpress sanitize_user函数以禁止用户名注册表格使用空格

问题描述

在wordpress中,sanitize_user()函数允许您定义应用于不同形式的限制规则。我在这里感兴趣的是注册表格,我正在尝试个性化此表格。我使用了WordPress主题作为我的登录插件,并且一切正常。但是,在注册过程中,我想防止用户输入带有空格的用户名。默认情况下,sanitize_user()函数允许使用带空格的用户名(例如:John Doe),但是我不想要它, 我只希望他们编写不带空格的用户名。

这是defaut sanitize_user()函数:

function sanitize_user( $username,$strict = false ) {
$raw_username = $username;
$username     = wp_strip_all_tags( $username );
$username     = remove_accents( $username );
// Kill octets.
$username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|','',$username );
// Kill entities.
$username = preg_replace( '/&.+?;/',$username );

// If strict,reduce to ASCII for max portability.
if ( $strict ) {
    $username = preg_replace( '|[^a-z0-9 _.\-@]|i',$username );
}

$username = trim( $username );
// Consolidate contiguous whitespace.
$username = preg_replace( '|\s+|',' ',$username );

/**
 * Filters a sanitized username string.
 *
 * @since 2.0.1
 *
 * @param string $username     Sanitized username.
 * @param string $raw_username The username prior to sanitization.
 * @param bool   $strict       Whether to limit the sanitization to specific characters.
 */
return apply_filters( 'sanitize_user',$username,$raw_username,$strict );

}

我试图将函数传递给严格但没有结果(function sanitize_user( $username,$strict = true ) {...};

有人可以帮我吗?

解决方法

尝试一下

add_filter( 'sanitize_user','remove_whitespace_from_username',10,3 );
function remove_whitespace_from_username( $username,$raw_username,$strict  ){
    $username = preg_replace('/\s+/',' ',$username);
    return $username;
}

您还可以使用以下代码删除空格

您还可以使用str_replace():-

$username = str_replce(' ','',$username); 

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...