简体   繁体   中英

Regex to match everything between the first and last occurrence of two distinct 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 the first ) .

I'm looking for what I would put in $regex that would match everything between the first ( and the last ) .

I'd appreciate the assistance.

Thanks in advance.

You can use this: -

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

/s modifier is used to enable the dot metacharacter to match everything including a newline. And, since .* is a greedy quantifier, it will match the longest string possible. So, it will match till the last ) .

Try this regular expression:

\([^\)]*\)

The first match is what you need.

Just do a greedy search

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM