Solved

PHP Regexp for Nested Parentheses

Posted on 2009-05-04
4
585 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

ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

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 …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
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.

770 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