Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern in JSON?

I'm trying to have a single JSON file to validate data both in front (JS) and back (PHP). I cannot figure out how to have my pattern in a json string, PHP won't convert it. Here's what I'd like to use (email validation):

'{"name":"email", "pattern":"^[a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,15})$"}'

I suppose there's something in pattern that doesn't get treated as a string? This as it is, won't convert to an object in PHP. I shouldn't have to escape anything but I might be wrong...

thanks

Edit: Tried this as suggested in comments:

json_decode('{"name":"email", "pattern":"^[a-z0-9]+(\\.[_a-z0-9]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,15})$"}‌​');  ==> NULL
like image 242
Eric Avatar asked Aug 21 '14 12:08

Eric


1 Answers

The problem are the backslashes \. Use two to signal that there is one and it will work well:

{"name":"email","pattern":"^[a-z0-9]+(\\.[_a-z0-9]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,15})$"}

The above is valid JSON but will cause trouble as PHP string, because \\ will already be interpreted as one \ before it is passed to json_decode(), and we're back where we started from. As deceze kindly pointed out in the comments, this can be solved by adding four backslashes:

{"name":"email","pattern":"^[a-z0-9]+(\\\\.[_a-z0-9]+)*@[a-z0-9-]+(\\\\.[a-z0-9-]+)*(\\\\.[a-z]{2,15})$"}

Or by immediately passing the contents from file_get_contents() (or similar) to json_decode().

like image 196
ljacqu Avatar answered Oct 20 '22 11:10

ljacqu