Winners2113
Winners2113

Reputation: 23

get all text between bracket but skip nested bracket

Im trying to figure out how to get the text between two bracket tags but dont stop at the first closing )

__('This is a (TEST) all of this i want') i dont want any of this;

my current pattern is __\((.*?)\)

which gives me

__('This is a (TEST) 

but i want

__('This is a (TEST) all of this i want') 

Thanks

Upvotes: 2

Views: 123

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626929

You may use a regex subroutine to match text inside nested parentheses after __:

if (preg_match_all('~__(\(((?:[^()]++|(?1))*)\))~', $s, $matches)) {
    print_r($matches[2]);
}

See the regex demo.

Details

  • __ - a __ substring
  • (\(((?:[^()]++|(?1))*)\)) - Group 1 (it will be recursed using the (?1) subroutine):
    • \( - a ( char
    • ((?:[^()]++|(?1))*) - Group 2 capturing 0 or more repetitions of any 1+ chars other than ( and ) or the whole Group 1 pattern is recursed
    • \) - a ) char.

See the PHP demo:

$s = "__('This is a (TEST) all of this i want') i dont want any of this; __(extract this)";
if (preg_match_all('~__(\(((?:[^()]++|(?1))*)\))~', $s, $matches)) {
    print_r($matches[2]);
}
// => Array ( [0] => 'This is a (TEST) all of this i want'  [1] => extract this )

Upvotes: 1

kzhao14
kzhao14

Reputation: 2630

Use the pattern __\((.*)?\).

The \ escapes the parentheses to catch literal parentheses. This then captures all the text inside that set of parentheses.

Upvotes: 0

Kévin Bibollet
Kévin Bibollet

Reputation: 3623

You forgot to escape two parenthesis in your regex : __\((.*)\);

Check on regex101.com.

Upvotes: 0

Related Questions