0

I need to validate some data and confirm that the pattern contains only a-z, A-Z, 0-9, full-stop or a forward slash.

if(!preg_match("/^[a-zA-Z0-9 ./]*$/",$field)) {  
 $fielderror = "Field can only contain a-z A-Z 0-9 . /";
}

However, it seems to allow other special characters e.g.: @ # and $.

any thoughts? Thinking i am missing something really obvious....

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Samuel
  • 11
  • 3

2 Answers2

1

You must only escape the / because is used as delimiter (is present at the start and end of the pattern):

if(!preg_match("/^[a-zA-Z0-9 .\/]*$/",$field)) {  
 $fielderror = "Field can only contain a-z A-Z 0-9 . /";
}

See here for more information about delimiters used in the regex.

user2342558
  • 5,567
  • 5
  • 33
  • 54
0

Your code has an error:

E_WARNING : type 2 -- preg_match(): Unknown modifier ']' -- at line 4

$field = "123";
//$field = "@*";


if(!preg_match("/^[a-zA-Z0-9 \.\/]+g/",$field)) {  
echo "Field can only contain a-z A-Z 0-9 . /";
} else {
echo "its ok";
}

You can use this regex:

^[a-zA-Z0-9\.\/]+
Pedram
  • 15,766
  • 10
  • 44
  • 73
  • Thanks Pedram, I gave this a try and whilst it works IF an invalid character is at the start, it does not seem to pickup if it is at the end. eg: $field = "Pizza@" seems to still get classed as ok. Any thoughts? Note: i tried your code here [link](http://phptester.net/) incase there is an issue with my php config etc. – Samuel Jan 23 '18 at 11:07
  • @Samuel Answer updated. Please check again. – Pedram Jan 23 '18 at 11:36
  • 1
    I was still able to key invalid characters, however this was mostliky because i was not using preg_match_all. in the end the code i used was: $p = '/[a-zA-Z0-9 \.\/]+/'; $psw1 = "password./"; preg_match_all($p, $psw1, $matches); $chkd = strlen(implode('', $matches[0])); if ($chkd != strlen($psw1)) { $p1err = "Password can only contain a-z A-Z 0-9 . /"; } – Samuel Jan 24 '18 at 01:30