问题
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.
回答1:
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));
回答2:
You're best off tackling this in stages. Only the first stage needs to use regex:
Find the entire string of coordinates as one glob, for example:
"4.885838 52.388063,4.891061 52.388381,4.890973 52.382909"
Split that string up into coordinate pairs separated by comma. In Python, we would use
str.split(',')
. I believe your PHP equivalent is calledexplode()
.[ "4.885838 52.388063" , "4.891061 52.388381" , "4.890973 52.382909" ]
Split each coordinate pair into two numbers separated by space:
str.split(' ')
.[ ["4.885838","52.388063"] , ["4.891061","52.388381"] , ["4.890973","52.382909"] ]
Convert to floats. In python we use
float()
: your local equivalent might be calledstr2float()
or similar.[ [4.885838,52.388063] , [4.891061,52.388381] , [4.890973,52.382909] ]
To find the string of numbers for step 1, try the regex
([-]?\d+.\d+ [-]?\d+.\d+)((,[-]?\d+.\d+ [-]?\d+.\d+)+)?
which finds at least one pair of coordinates in x y
format, with coordinate pairs separated by commas. You can see the regular expression in action on regexr.
来源:https://stackoverflow.com/questions/10579889/which-regular-expression-to-use-to-convert-this-string-to-an-array