duanheyi7147 2014-08-21 12:33
浏览 845
已采纳

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
  • 写回答

1条回答 默认 最新

  • douyuan4697 2014-08-21 12:37
    关注

    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().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题