I am trying to only allow one single character suing regex but it seems that it is allowing multiple amounts through.
I have tried this..
$char = trim($_REQUEST['char']);
/* Validate char */
if (preg_match('/[^a-zA-Z]{1}/', $char)) {
$char = 'a';
}
echo $char;
and this..
$char = trim($_REQUEST['char']);
/* Validate char */
if (!preg_match('/[a-zA-Z]{1}/', $char)) {
$char = 'a';
}
echo $char;
But neither work. They always output the result even if $_REQUEST['char'] is equal to aa.
You’re matching one character, but you aren’t matching only one character. Any string with at least one alpha character will pass your current regex.
The
^indicates the start of the string, and the$indicates the end. No need for the{1}in this case.You could alternatively check
strlen($char) == 1in theifstatement.