Regex pattern in JSON?
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()
.
Comments
-
Eric almost 2 years
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
-
Eric over 9 yearsThere must be something else, I've tried that too. Still won't parse
-
Eric over 9 yearsjson_decode('{"name":"email", "pattern":"^[a-z0-9]+(\\.[_a-z0-9]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,15})$"}'); ==> NULL
-
Gromski over 9 years@Eric If you're writing it as a PHP string literal (as opposed to reading it from a file, for example) you'll need an additional backslash for each backslash.
-
Eric over 9 yearsDo you mean triple backslash for a backslash ?
-
ljacqu over 9 yearsIndeed, \ has to be \\\\ in PHP.
{"name":"email","pattern":"^[a-z0-9]+(\\\\.[_a-z0-9]+)*@[a-z0-9-]+(\\\\.[a-z0-9-]+)*(\\\\.[a-z]{2,15})$"}
works. But the one in my post is valid JSON. I'll do a test with JavaScript and I'll update my post in a bit. -
Gromski over 9 years@Eric Quadruple backslash for each backslash. Tip: write the plain regex into a file, then:
var_export(json_encode(array('pattern' => file_get_contents('regex.txt'))));
This'll "reverse engineer" the valid syntax. -
ljacqu over 9 yearsThanks for the comments @deceze, I hope it's OK that I've linked to your profile in my update.