Php 如何使用ctype_alnum()允许下划线和破折号?

Php 如何使用ctype_alnum()允许下划线和破折号?,php,regex,Php,Regex,使用时,如何将\uuu和-的异常添加为有效字符 我有以下代码: 由于ctype_alnum只验证字母数字字符, 试试这个: $sUser = 'my_username01'; $aValid = array('-', '_'); if(!ctype_alnum(str_replace($aValid, '', $sUser))) { echo 'Your username is not properly formatted.'; } 也许可以改用preg\u match if(pr

使用时,如何将
\uuu
-
的异常添加为有效字符

我有以下代码:
由于ctype_alnum只验证字母数字字符, 试试这个:

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

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

也许可以改用
preg\u match

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

下面是如何使用ctype_alnum和异常,在本例中,我还允许使用连字符(或语句)

$oldString=$input\u code;
$newString='';
$strLen=mbu strLen($oldString);
对于($x=0;$x<$strLen;$x++)
{
$singleChar=mb_substr($oldString,$x,1);
if(ctype_alnum($singleChar)或($singleChar=='-'))
{
$newString=$newString.$singleChar;
}
}
$input_code=strtoupper($newString);

regex等价物非常简短,易于阅读

~^[\w-]+$~
此模式要求整个字符串由一个或多个字母、数字、下划线或连字符组成

Regex允许您跳过数据准备步骤,直接访问评估——从而生成更干净、更精简、更直接、看起来更专业的代码

if (preg_match('~^[\w-]+$~', $username)) {
    return true;
} else {
    $this->form_validation->set_message(
        '_check_username',
        'Invalid username! Alphanumerics, underscores, and hyphens only.'
    );
    return false;
}

很抱歉@minitech我没有8K的声誉需要了解this@minitech这意味着对我来说,stru_替换比preg_匹配更容易理解。这个答案非常受欢迎。这个解决方案似乎非常低效。
$oldString = $input_code;
$newString = '';
$strLen = mb_strlen($oldString);
for ($x = 0; $x < $strLen; $x++) 
   {
     $singleChar = mb_substr($oldString, $x, 1);
     if (ctype_alnum($singleChar) OR ($singleChar == '-'))
        {
          $newString = $newString . $singleChar;
        }
   }
$input_code = strtoupper($newString);
if (preg_match('~^[\w-]+$~', $username)) {
    return true;
} else {
    $this->form_validation->set_message(
        '_check_username',
        'Invalid username! Alphanumerics, underscores, and hyphens only.'
    );
    return false;
}