I am very poor in writing regular expression.
I am trying to get value between brackets "()". Something like below...
$a = "POLYGON((1 1,2 2,3 3,1 1))";
preg_match_all("/\((.*)\)/U", $a, $pat_array);
print_r($pat_array);
But this will give me elements like...
Array
(
[0] => Array
(
[0] => ((1 1,2 2,3 3,1 1)
)
[1] => Array
(
[0] => (1 1,2 2,3 3,1 1
)
)
But i want to fetch "1 1,2 2,3 3,1 1" as a output.
I know we can trim the brackets after getting this output. But this will be great if it done using Regular Expression.
Thanks in advance.
Using @anubhava's regular expression.
Example:
$a = "POLYGON((1 1,2 2,3 3,1 1),(1 1,2 2,3 3,1 1),(1 1,2 2,3 3,1 1))";
And if print result of this regular expression you will get like this...
Array
(
[0] => Array
(
[0] => ((1 1,2 2,3 3,1 1)
[1] => (1 1,2 2,3 3,1 1)
[2] => (1 1,2 2,3 3,1 1))
)
[1] => Array
(
[0] => 1 1,2 2,3 3,1 1
[1] => 1 1,2 2,3 3,1 1
[2] => 1 1,2 2,3 3,1 1
)
)
Look at second array element, it's exactly like we want.
FYI: I have used it for Fetching GEOMETRY Data of POLYGON from MySQL Database and then i processed it with array to get all Latitude and Longitude of all Polygon Nodes.
Use negation based regex pattern and get your result from captured group #1:
preg_match_all('/\(+([^()]*)\)+/', $a, $pat_array);
print_r($pat_array[1]);
[^()]*
will match any char that is not (
or )
.
Output:
Array
(
[0] => 1 1,2 2,3 3,1 1
)
Use lookarounds
preg_match_all("/(?<=\()[^()]*(?=\))/U", $a, $pat_array);
See demo.
https://regex101.com/r/vV1wW6/42
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With