-3

I am writing some code that expects to receive a block of html which is always going to include the following:

var code = [39.474, -0.3548];

The value between the square brackets is always going to be different. How could I extract the value between the square brackets using php?

I should probably point out that I am parsing a block of HTML to php that includes js aswell.

jk1001
  • 13
  • 5

3 Answers3

1

Use a regular expression like

preg_match_all('/\\[(.*?)\\]/', $your_string, $matches, PREG_SET_ORDER);

The array $matches[1] then will contain your values.

syck
  • 2,984
  • 1
  • 13
  • 23
0

If the Javascript array format will be kept constant (always two components and a space after ','), you can use /(?:\[)(.*)[,][ ](.*)(?:\])/ regex to extract them in php:

$line = 'var code = [39.474, -0.3548];';

preg_match("/(?:\[)(.*)[,][ ](.*)(?:\])/", $line, $output_array);

print_r ($output_array);

The result will be

array(
0   =>  [39.474, -0.3548]
1   =>  39.474
2   =>  -0.3548
)
Ivan De Paz Centeno
  • 3,595
  • 1
  • 18
  • 20
-1

A quick and dirty solution may be:

  1. Replace "[" and "]"
  2. explode by ","

    $a = "[39.474, -0.3548]"; $b = str_replace("]", "", str_replace("[", "", $a)); $c = explode(",", $b); print_r($c);

Output:

Array ( [0] => 39.474 [1] => -0.3548 )
B001ᛦ
  • 2,036
  • 6
  • 23
  • 31