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
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
Share
Improve this question
edited Aug 21, 2014 at 12:46
Eric
asked Aug 21, 2014 at 12:33
EricEric
10.6k14 gold badges71 silver badges111 bronze badges
5
- I'm not sure what you're asking. What does "PHP won't convert it" mean? What is the result in PHP? Using what code? – deceze ♦ Commented Aug 21, 2014 at 12:38
- json_decode(mystring) – Eric Commented Aug 21, 2014 at 12:39
- 2 Nope. Also not a duplicate, my object structure is fine. – Eric Commented Aug 21, 2014 at 12:40
- Your object structure yes, your syntax no. jsonlint.com – deceze ♦ Commented Aug 21, 2014 at 12:41
- @deceze : jsonlint valid the answer of ljacqu. If the owner's problem persist, it's coming from another part of his code. – Debflav Commented Aug 21, 2014 at 12:43
1 Answer
Reset to default 16The 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()
.