1

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

Community
  • 1
  • 1
user3808307
  • 2,270
  • 9
  • 45
  • 99
  • @lleaff beat me to the answer, but I wanted to mention that I use https://regex101.com/ to test my regex implementations. It's pretty awesome and will let you test against JS, PHP, and python. It is also smart enough to highlight your errors for you :) – Wesley Smith Dec 29 '15 at 04:42
  • Even though you have edited your regex above, the issue is still the same, lack of escaping the `/`, and the solution provided by lleaff is still valid. Rather that changing the regex here, try playing with your permutations in the regex101.com website. You'll likely find that you are able to fix many future problems yourself :) – Wesley Smith Dec 29 '15 at 04:51
  • `RegExp` is a javascript construct, not specific to jQuery. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp – chris85 Dec 29 '15 at 04:56

1 Answers1

2

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.

Community
  • 1
  • 1
lleaff
  • 4,249
  • 17
  • 23
  • Thank you very much to everyone, sorry about the editing and unediting, I tried putting the question back to the way it was when I saw it had already been answered and I made a mess. I will try regex 101 now. Thanks . – user3808307 Dec 29 '15 at 04:55
  • @user3808307 use the `rollback` feature in the edit features. – chris85 Dec 29 '15 at 04:58