Search code examples
phpregexgeojson

Which regular expression to use to convert this string to an array?


From a geospatial column in mysql I'm getting the following string-value which I want to convert into an array. Ultimate goal is to convert it to geoJSON.

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

This string has 3 coordinate pairs with the x and y coordinate separated by a space and the pairs separated with a comma. The exact number is not known and variable. Also the POLYGON can differ to three different settings.

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

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

With the part of the coordinates with the double brackets as an uncertain part.

Could 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.

Solution

  • I think it's easier and more maintainable to just use explode and array_map on the coordinate string:

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