[Solved] What’s the proper syntax in preg_match for validating a string if it contains a alphanumeric value w/ special characters [closed]


If you want to test if a string contains at least one alphanumeric and at least one non-alphanumeric string, use the following regex:

/^(?=.*[a-z0-9])(?=.*[^a-z0-9])/i

Breakup:

  • / start of regex
  • ^ match the start of the string
  • (?= if the following is present there:
    • .* anything at all (except newlines), then
    • [a-z0-9] an alphanumeric character
  • ) end of lookahead
  • (?= and if the following is present there:
    • .* anything at all (except newlines), then
    • [^a-z0-9] a non-alphanumeric character
  • ) end of lookahead
  • / end of regex
  • i case-insensitive

usage:

if(preg_match("/^(?=.*[a-z0-9])(?=.*[^a-z0-9])/i",$newPass)) {
    //is valid..
}

If you require letters and digits to both be present, replace the first lookahead by two:

/^(?=.*[a-z])(?=.*[0-9])(?=.*[^a-z0-9])/i

2

solved What’s the proper syntax in preg_match for validating a string if it contains a alphanumeric value w/ special characters [closed]