Jamie Obrien Jamie Obrien - 6 months ago 38
PHP Question

My Regex is not working all of a sudden?

I have a regex which I am testing to validate my register form, the regex worked perfectly a few days ago and now all of a sudden even if I match the regex in the form which is validated client side and passes (same regex) and then the server side is spitting out the else statement saying I am not matching the regex each time now. Any clues guys?

$usern = $_POST['username'];
$regex = '(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{3,}';

$Access = preg_match($regex, $usern);

//database stuff here
echo "You filled the form out incorrectly!";


The main issue are the missing delimiters, but as best practice, it is also a good idea to add an ^ anchor:

$regex = '~^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{3,}~';

Validation regexps are usually built with the principle of contrast in mind, and your regex is more efficient when you rewrite it like

$regex = '~^(?=\D*\d)(?=[^a-z]*[a-z])(?=[^A-Z]*[A-Z]).{3,}~';

So, the regex will (in)validate the input faster without the redundant backtracking caused by .* in the lookaheads.