Convert Javascript Regular Expression to PHP (PCRE) Expression

Posted by Matt on Stack Overflow See other posts from Stack Overflow or by Matt
Published on 2010-03-18T06:41:01Z Indexed on 2010/03/18 6:41 UTC
Read the original article Hit count: 648

Filed under:
|
|
|

Hi all,

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() [function.preg-match-all]: Compilation failed: nothing to repeat at offset 0 in /Users/Matt/Sites/Templating/json/Jeeves.php on line 88

Any help would be much appreciated!

Thanks, Matt

© Stack Overflow or respective owner

Related posts about regex

Related posts about php