使用哪个正则表达式将此字符串转换为数组? [英] Which regular expression to use to convert this string to an array?
问题描述
从mysql的地理空间列中,我获取了以下要转换为数组的字符串值.最终目标是将其转换为geoJSON.
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))
此字符串具有3个坐标对,其中x和y坐标之间用空格分隔,而该对之间用逗号分隔.确切的数字是未知的并且是可变的.此外,POLYGON
可以具有三种不同的设置.
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.
以我对reg的一点了解.我想出的表达式:
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.
有人可以帮我吗?
编辑最终,结果数组应如下所示:
edit Ultimately the resulting array should look like this:
$array['type'] = POLYGON | LINESTRING ....
$array['coordinates'] = array of all the coordinates.
推荐答案
我认为只使用 explode 并在坐标字符串上 array_map :
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));
这篇关于使用哪个正则表达式将此字符串转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!