如何使用ctype_alnum()允许下划线和短划线?

Tri*_*tan 9 php regex

使用ctype_alnum()时,如何添加_-作为有效字符的例外?

我有以下代码:

if ( ctype_alnum ($username) ) {

  return TRUE;

} elseif (!ctype_alnum  ($username)) {

  $this->form_validation->set_message(
    '_check_username',
    'Invalid username! Alphanumerics only.'
  );

  return FALSE;
}
Run Code Online (Sandbox Code Playgroud)

Boo*_*eus 19

由于ctype_alnum仅验证字母数字字符,请尝试以下操作:

$sUser = 'my_username01';
$aValid = array('-', '_');

if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
    echo 'Your username is not properly formatted.';
} 
Run Code Online (Sandbox Code Playgroud)

  • 比正则表达还快. (11认同)
  • 对不起@minitech我没有8K的声誉来理解这一点 (3认同)
  • @ Tech4Wilco:是的,但不太清楚. (2认同)

Ry-*_*Ry- 5

preg_match也许可以使用吗?

if(preg_match("/^[a-zA-Z0-9_\-]+$/", $username)) {
    return true;
} else {
    $this->form_validation->set_message('_check_username', 'Invalid username! Alphanumerics only.');
}
Run Code Online (Sandbox Code Playgroud)