JSON中的正则表达式模式? [英] Regex pattern in JSON?
问题描述
我正在尝试使用单个JSON文件来验证前端(JS)和后端(PHP)中的数据。
我无法弄清楚如何在json字符串中使用我的模式,PHP不会转换它。
这是我想要使用的内容(电子邮件验证):
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})$"}'
我想模式中的某些内容不会被视为字符串?实际上,它不会转换为PHP中的对象。我不应该逃避任何事情,但我可能错了......
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...
谢谢
编辑:试过这在评论中建议:
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
推荐答案
问题是反斜杠 \
。用两个来表示有一个它会运行良好:
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})$"}
以上是有效的JSON但会导致PHP字符串出现问题,因为 \\
已经被解释为一个 \
在传递给 json_decode()
之前,我们回到了我们开始的地方。正如 deceze 在评论中指出的那样,这可以通过添加四个反斜杠来解决:
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})$"}
或者立即从<$传递内容c $ c> file_get_contents()(或类似)到 json_decode()
。
Or by immediately passing the contents from file_get_contents()
(or similar) to json_decode()
.
这篇关于JSON中的正则表达式模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!