dsyak22488 2010-03-18 06:41
浏览 138
已采纳

将Javascript正则表达式转换为PHP(PCRE)表达式

I am up to my neck in regular expressions, and I have this regular expression that works in javascript (and flash) that I just can't get working in PHP

Here it is:

  var number
      = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
  var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'
      + '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
  var str = '(?:\"' + oneChar + '*\")';
  var varName = '\\$(?:' + oneChar + '[^ ,]*)';
  var func = '(?:{[ ]*' + oneChar + '[^ ]*)';
  // Will match a value in a well-formed JSON file.
  // If the input is not well-formed, may match strangely, but not in an unsafe
  // way.
  // Since this only matches value tokens, it does not match whitespace, colons,
  // or commas.
  var jsonToken = new RegExp(
      '(?:false|true|null'
      +'|[\\}]'
      + '|' + varName
      + '|' + func
      + '|' + number
      + '|' + str
      + ')', 'g');

If you want it fully assembled here it is:

/(?:false|true|null|[\}]|\$(?:(?:[^\0-\x08\x0a-\x1f"\\]|\\(?:["/\\bfnrt]|u[0-9A-Fa-f]{4}))[^ ,]*)|(?:{[ ]*(?:[^\0-\x08\x0a-\x1f"\\]|\\(?:["/\\bfnrt]|u[0-9A-Fa-f]{4}))[^ ]*)|(?:-?\b(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b)|(?:"(?:[^\0-\x08\x0a-\x1f"\\]|\\(?:["/\\bfnrt]|u[0-9A-Fa-f]{4}))*"))/g

Interestingly enough, its very similar to JSON.

I need this regular expression to work in PHP...

Here's what I have in PHP:

    $number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';
    $oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
    $string = '(?:\"'.$oneChar.'*\")';
    $varName = '\\$(?:'.$oneChar.'[^ ,]*)';
    $func = '(?:{[ ]*'.$oneChar.'[^ ]*)';

    $jsonToken = '(?:false|true|null'
      .'|[\\}]'
      .'|'.$varName
      .'|'.$func
      .'|'.$number
      .'|'.$string
      .')';

    echo $jsonToken;

    preg_match_all($jsonToken, $content, $out);

    return $out;

Here's what happens if I try using preg_match_all():

Warning: preg_match_all() failed: nothing to repeat at offset 0 on line 88

Any help would be much appreciated!

Thanks, Matt

  • 写回答

2条回答 默认 最新

  • douyan1921 2010-03-18 06:46
    关注

    I guess this is happening because you don't have your regex between the delimiters.

    Try:

    $jsonToken = '@(?:false|true|null'
          .'|[\\}]'
          .'|'.$varName
          .'|'.$func
          .'|'.$number
          .'|'.$string
          .')@';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料