user3808307 user3808307 - 4 years ago 239
PHP Question

Convert JQuery RegEx into PHP RegEX

Sorry for this question as it is very specific.

I have a

JQuery validation RegEx
that I would like to use on the back end too:

var forNames = new RegExp("^[^0-9<>'\"/;`%]*$");


I tried in
PHP


preg_match('/^[^0-9<>\'\"/;`%]{2,42}$/', $first_name) // I also want to keep the length between 2 and 42 here)


but it does not work, I get Unknown modifier ';' in

The other question, similar to this one is what this person is asking here

Converting Javascript Regex to PHP

I tried his solution, copying the
php email validation regex
into
JQuery
with no luck

Thank you

Ps I just unedited what i had added to the regex cause i didnt see it already had answers and it was confusing

Answer Source

You need to escape the / character in your PHP regex string, because that's also the character which is used to signify the end of a regexp (it's called a delimiter):

preg_match('/^[^0-9<>\'\"/;`%]{2,42}$/', $first_name) 
                         ^

becomes:

preg_match('/^[^0-9<>\'\"\/;`%]{2,42}$/', $first_name) 

The reason you didn't need to do this in your JavaScript code is that you used the RegExp constructor, which essentially automatically escaped it for you. If you had used a RegExp literal you would have had to escape it too:

var forNames = /^[^0-9<>'\"\/;`%]*$/;

As @DelightedD0D commented, make sure to test your RegExp with an interactive tool like regex101, it supports both PHP and JS style regexp and is actually how I was able to catch your error so fast.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download