What regular expression is used to convert this string to an array?

From the geospatial column in mysql, I get the following string value that I want to convert to an array. The ultimate goal is to convert it to geoJSON.

POLYGON((4.885838 52.388063,4.891061 52.388381,4.890973 52.382909))

This line has 3 coordinate pairs with x and y coordinates separated by a space and pairs separated by a comma. The exact number is unknown and variable. It POLYGONmay also differ from three different settings.

With my little knowledge reg. I came up with this:

$pat = '/^(POLYGON|LINESTRING|POINT)(\(\() (.....) (\)\))$/';
preg_match($pat, $str, $matches);

With a part of coordinates with double brackets as an undefined part.

Can anyone help me with this?

edit Ultimately, the resulting array should look like this:

$array['type'] = POLYGON | LINESTRING ....
$array['coordinates'] = array of all the coordinates.
+3
source share
2 answers

, explode array_map :

$coordString = $matches[3];
$coordinates = array_map(function($e) { return explode(' ', $e); },
                         explode(',', $coordString));
0

. :

  • , :

    "4.885838 52.388063,4.891061 52.388381,4.890973 52.382909"

  • , . Python str.split(','). , PHP explode().

    [ "4.885838 52.388063" , "4.891061 52.388381" , "4.890973 52.382909" ]

  • , : str.split(' ').

    [ ["4.885838","52.388063"] , ["4.891061","52.388381"] , ["4.890973","52.382909"] ]

  • . python float(): str2float() .

    [ [4.885838,52.388063] , [4.891061,52.388381] , [4.890973,52.382909] ]

1,

([-]?\d+.\d+ [-]?\d+.\d+)((,[-]?\d+.\d+ [-]?\d+.\d+)+)?

x y , . regexr.

+2

All Articles