Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to take value between brackets "()"?

Tags:

regex

php

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.


Solution: as per @anubhava answer:

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.

like image 990
Mihir Vadalia Avatar asked Sep 27 '22 14:09

Mihir Vadalia


2 Answers

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
)
like image 104
anubhava Avatar answered Oct 19 '22 09:10

anubhava


Use lookarounds

preg_match_all("/(?<=\()[^()]*(?=\))/U", $a, $pat_array);

See demo.

https://regex101.com/r/vV1wW6/42

like image 1
vks Avatar answered Oct 19 '22 09:10

vks