const regex = new RegExp('\\s* # white spaces
########################## KEYS START ##########################
(?: # We\\\\'ll use this to make keys optional
(?P<keys> # named group: keys
\\d+ # match digits
| # or
"(?(?=\\\\\\\\")..|[^"])*" # match string between "", works even 4 escaped ones "hello \\" world"
| # or
\\\\'(?(?=\\\\\\\\\\\\')..|[^\\\\'])*\\\\' # match string between \\\\'\\\\', same as above :p
| # or
\\$\\w+(?:\\[(?:[^[\\]]|(?R))*\\])* # match variables $_POST, $var, $var["foo"], $var["foo"]["bar"], $foo[$bar["fail"]]
) # close group: keys
########################## KEYS END ##########################
\\s* # white spaces
=> # match =>
)? # make keys optional
\\s* # white spaces
########################## VALUES START ##########################
(?P<values> # named group: values
\\d+ # match digits
| # or
"(?(?=\\\\\\\\")..|[^"])*" # match string between "", works even 4 escaped ones "hello \\" world"
| # or
\\\\'(?(?=\\\\\\\\\\\\')..|[^\\\\'])*\\\\' # match string between \\\\'\\\\', same as above :p
| # or
\\$\\w+(?:\\[(?:[^[\\]]|(?R))*\\])* # match variables $_POST, $var, $var["foo"], $var["foo"]["bar"], $foo[$bar["fail"]]
| # or
array\\s*\\((?:[^()]|(?R))*\\) # match an array()
| # or
\\[(?:[^[\\]]|(?R))*\\] # match an array, new PHP array syntax: [1, 3, 5] is the same as array(1,3,5)
| # or
(?:function\\s+)?\\w+\\s* # match functions: helloWorld, function name
(?:\\((?:[^()]|(?R))*\\)) # match function parameters (wut), (), (array(1,2,4))
(?:(?:\\s*use\\s*\\((?:[^()]|(?R))*\\)\\s*)? # match use(&$var), use($foo, $bar) (optionally)
\\{(?:[^{}]|(?R))*\\} # match { whatever}
)?;? # match ; (optionally)
) # close group: values
########################## VALUES END ##########################
\\s* # white spaces', 'smg')
const str = `0 => "a", 123 => 123, 1234, 'got problem ?',
"a" => \$GlobalScopeVar,
\$test_further => function test(\$noway){echo "this works too !!!";},
"yellow" => "blue",
"b" => array("nested"=>array(1,2,3), "nested"=>array(1,2,3),"nested"=>array(1,2,3)),
"c" => function() use (&\$VAR) { return isset(\$VAR) ? "defined" : "undefined" ; },
"bug",\$var = \$_POST["test];
"fixed",
"mwahahahaa" => "Yeaaaah",
\$_POST["hello"][\\'world\\'] => array("is", "actually", "An array !")`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions