How can I add the exception of _
and -
as valid characters when using 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;
}
Since ctype_alnum only validates alpha numeric character, Try this:
$sUser = 'my_username01';
$aValid = array('-', '_');
if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
echo 'Your username is not properly formatted.';
}
Use preg_match
instead, maybe?
if(preg_match("/^[a-zA-Z0-9_\-]+$/", $username)) {
return true;
} else {
$this->form_validation->set_message('_check_username', 'Invalid username! Alphanumerics only.');
}
Here is how to use ctype_alnum AND have exceptions, in this case I also allow hyphens ( OR statement).
$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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With