I have few questions regarding preg_match in php.
if(preg_match('#[^0-9 -&()+@._A-Za-z]#', $input)){
$errors .= 'Sorry, username can\'t contain those characters.<br>';
}
This is my preg_match
. I am kinda new to these codes. I have red that its better to use #
on the end and beginning than /
for unknown reason xD
Anyone knows what is up with that?
My main problem is that this preg_match
actually let strings with %
(percent signs) through and it shouldn't. Why? and how to stop that?
Another question is this preg_match
code good?
It works fine (except %
part) but can it fail?
Thank you :)
this preg_match actually let strings with "%" (percent signs) through and it shouldn't. Why?
That is due to unescaped hyphen in the middle of your regex:
'#[^0-9 -&()+@._A-Za-z]#'
--------^
-
is acting as range from space (32) to &
(38) thus matching anything in between including %
( 37).
It should be used as:
'#[^-0-9 &()+@._A-Za-z]#'
Or
'#[^-\w &()+@.]#'
However without anchors this character class will match only one character. You should use:
'#^[^-\w &()+@.]+$#'