Solved

PHP Regexp for Nested Parentheses

Posted on 2009-05-04
4
576 Views
Last Modified: 2012-06-27
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
Comment
Question by:guyharleyaus
  • 2
4 Comments
 
LVL 84

Expert Comment

by:ozo
ID: 24302139
if rhe parentheses are only nested two deep, you could do
/(\((?:\([^()]*\)|[^()]+)*\))/
0
 

Author Comment

by:guyharleyaus
ID: 24302182
The parentheses can be nest multiple layers e.g.

(some (text (with (nested) parentheses) and) (other stuff))
0
 
LVL 84

Accepted Solution

by:
ozo earned 50 total points
ID: 24302448
/(\((?:(?>[^()]+|(?R))*)\))/
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now