Regex to match everything between the first and last occurrence of two different characters

I have the following code:

$str_val = "L(ine 1( L(ine 2) Line 3 Line 4)"; $regex = '/\(([^\)]*?)\)/i'; preg_match($regex, $str_val, $matches_arr); print_r($matches_arr); 

This code matches everything between the first ( and first ) .

I am looking for what I would add to $regex , which would match everything between the first ( and last ) .

I would be grateful for the help.

Thanks in advance.

+4
source share
3 answers

You can use this: -

 '/\((.*)\)/s' 
Modifier

/s used to include the point metacharacter with everything, including a new line. And since .* Is a greedy quantifier, it will match the longest line. Thus, it will correspond to the latter ) .

+2
source

Try this regex:

 \([^\)]*\) 

The first match is what you need.

0
source

Just do a greedy search

 $regex = '/\(.*\)/s'; 

If you really want to have everything in between (...) , use this

 $regex = '/\((.*)\)/s'; preg_match($regex, $str_val, $matches_arr); echo $matches_arr[1]; 
0
source

All Articles