J B
J B

Reputation: 9

PHP Regex get the value from JavaScript code

I have a problem with designing a regular expression to extract a value from JavaScript code.
I need to find the line where Array('38') is and get the numeric value of the Math.floor function's argument there.

Given this code, the result would be 296:

addCombination(158, new Array('38'), -9, Math.floor(296), 0, -1, 'LB229');
addCombination(159, new Array('39'), -2, Math.floor(221), 0, -1, 'LB201');
addCombination(160, new Array('40'), -2, Math.floor(201), 0, -1, 'LB243');

Thanks for advice.

Upvotes: 0

Views: 53

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627409

Here is an example PHP code you might use to extract the Math.floors:

<?php
   $str = "addCombination(158, new Array('38'), -9, Math.floor(296), 0, -1, 'LB229');\naddCombination(159, new Array('38'), -2, Math.floor(221), 0, -1, 'LB201');\naddCombination(160, new Array('38'), -2, Math.floor(201), 0, -1, 'LB243');";
   preg_match_all("/Math\\.floor\\(\\K\\d+(?=\\))/", $str, $matches);
   foreach ($matches[0] as $line)
   {
       echo $line . "\n";
   }
?>

Output:

296                                                                                                                                                                                                                                                    
221                                                                                                                                                                                                                                                    
201

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174836

You could achieve this through a single regex.

^(?=.*\bArray\('38'\)).*?\bMath\.floor\(\K\d+

DEMO

  • (?=.*\bArray\('38'\)) would match at the start of a line only if the line contains the text Array('38').

  • And the following .*?\bMath\.floor\( matches all the chars on that line from the start until Match.floor( string.

  • \K discards the previous match.

  • \d+ matches the number present inside the Math.floor function.

Example:

$s = <<<EOT
addCombination(158, new Array('38'), -9, Math.floor(296), 0, -1, 'LB229');
addCombination(159, new Array('39'), -2, Math.floor(221), 0, -1, 'LB201');
addCombination(160, new Array('40'), -2, Math.floor(201), 0, -1, 'LB243');
EOT;
preg_match_all("~^(?=.*\bArray\('38'\)).*?\bMath\.floor\(\K\d+~m", $s, $matches);
print_r($matches[0]);

Output:

Array
(
    [0] => 296
) 

Upvotes: 1

Related Questions