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条)

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试