[英]Convert Javascript Regular Expression to PHP (PCRE) Expression
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 我在正则表达式中依靠我的脖子,我有这个正则表达式,在javascript(和flash)中工作,我无法在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. 有趣的是,它与JSON非常相似。
I need this regular expression to work in PHP... 我需要这个正则表达式在PHP中工作...
Here's what I have in PHP: 这是我在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(): 如果我尝试使用preg_match_all(),会发生以下情况:
Warning: preg_match_all() [function.preg-match-all]: Compilation failed: nothing to repeat at offset 0 on line 88 警告:preg_match_all()[function.preg-match-all]:编译失败:无法在第88行的偏移0处重复
Any help would be much appreciated! 任何帮助将非常感激!
Thanks, Matt 谢谢,马特
In preg
, the delimiter is needed in the pattern, eg you use it as 在preg
,模式中需要分隔符,例如,您将其用作
preg_match_all('#[a-z]+#i', ....); // # is the delimiter, i means case-insensitive.
Try to add them and see if there're still any errors. 尝试添加它们,看看是否还有任何错误。
I guess this is happening because you don't have your regex between the delimiters . 我想这种情况正在发生,因为你没有在分隔符之间使用你的正则表达式 。
Try: 尝试:
$jsonToken = '@(?:false|true|null'
.'|[\\}]'
.'|'.$varName
.'|'.$func
.'|'.$number
.'|'.$string
.')@';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.