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

£可爱£侵袭症+ 提交于 2019-12-12 16:17:06

问题


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:

  1. Find the entire string of coordinates as one glob, for example:

    "4.885838 52.388063,4.891061 52.388381,4.890973 52.382909"

  2. Split that string up into coordinate pairs separated by comma. In Python, we would use str.split(','). I believe your PHP equivalent is called explode().

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

  3. Split each coordinate pair into two numbers separated by space: str.split(' ').

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

  4. Convert to floats. In python we use float(): your local equivalent might be called str2float() 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!