【问题标题】:Why does this pattern not work in preg_match()?为什么这种模式在 preg_match() 中不起作用?
【发布时间】:2013-06-08 12:19:14
【问题描述】:

http://gskinner.com/RegExr/?355lr

它在那个正则表达式中运行良好。如果我像这样将它插入到我的 preg_match() 中:

$reason = preg_match('/(?<=error\: )(.*?)(?=\; Request)/', $message);

它总是返回一个 0。

我认为它与 preg_match() 期望模式被格式化的方式有关?

【问题讨论】:

  • 它对我来说很好用。
  • 似乎我有一个不在正则表达式示例中的杂散换行符,但我的错误正在输出。谢谢。

标签: regex preg-match delimiter


【解决方案1】:

对我来说似乎没问题。检查 $message 是否未转义或与该正则表达式有任何不同。

$message = 'Request have return error: Invalid email syntax; Request: {"jsonrpc":"2.0","method":"add_contact","params":["420a42ea1685c9a273f26378aa82081b",{"campaign":"nfzM","name":"Chris Allen","email":"eric","ip":"127.0.0.1","customs":[{"name":"phone","content":"123456"},{"name":"address","content":"123 Fake Street"},{"name":"city","content":"Chicago"},{"name":"state","content":"IL"},{"name":"zipcode","content":"0001"},{"name":"country","content":"United States"},{"name":"company_name","content":"Acme"},{"name":"store_url","content":"http:\/\/www.google.com"},{"name":"timestamp","content":"06.10.13"},{"name":"subscriber_ip","content":"127.0.0.1"}]}],"id":2};';

$reason = preg_match('/(?<=error\: )(.*?)(?=\; Request)/', $message);

var_dump($reason);

回馈:

int(1)

【讨论】:

    【解决方案2】:

    尝试改用这个正则表达式,因为您使用过 '?'切换贪婪:

    $reason = preg_match('/(?<=error\: )(.*)(?=\; Request)/', $message);`
    

    【讨论】:

      【解决方案3】:

      我认为您的问题不在于您的正则表达式本身,还要注意 ;: 不需要转义。但是我建议你使用这个:

      if (preg_match('~error: \K[^;]++(?=; Request)~', $message, $reason))
          print_r($reason);
      

      注意$reason

      在哪里

      【讨论】:

        猜你喜欢
        • 2014-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-23
        • 1970-01-01
        • 2012-03-20
        相关资源
        最近更新 更多