• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 605
  • Last Modified:

PHP Regexp for Nested Parentheses

I have a chunk of text in the form:

some text (more (text) with (possible nested) parentheses) (yet more (text) with (possible nested) parentheses) final text

I want to get the first set of nested parentheses i.e.

 (more (text) with (possible nested) parentheses)

I've tried preg_match("/\(([^\)]+|(?R))\)*/is",$text,$matches) but it gives me all the parenthses i.e.

(more (text) with (possible nested) parentheses) (yet more (text) with (possible nested) parentheses)

I've also tried preg_match("/\(([^\)]+|(?R))\)*/is",$text,$matches) but this produces eratic results (sometimes chopping off stuff after a nested closing parenthesis, sometimes not).

Any sugestions?
0
guyharleyaus
Asked:
guyharleyaus
  • 2
1 Solution
 
ozoCommented:
if rhe parentheses are only nested two deep, you could do
/(\((?:\([^()]*\)|[^()]+)*\))/
0
 
guyharleyausAuthor Commented:
The parentheses can be nest multiple layers e.g.

(some (text (with (nested) parentheses) and) (other stuff))
0
 
ozoCommented:
/(\((?:(?>[^()]+|(?R))*)\))/
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now