?
Solved

PHP Regexp for Nested Parentheses

Posted on 2009-05-04
4
Medium Priority
?
599 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
3 Comments
 
LVL 85

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 85

Accepted Solution

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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

It’s a season to be thankful, and we’re thankful for users like you who engage on site, solve technology problems, and network with others in the industry. What tech are we most thankful for? Keep reading.
The title says it all. Writing any type of PHP Application or API code that provides high throughput, while under a heavy load, seems to be an arcane art form (Black Magic). This article aims to provide some general guidelines for producing this typ…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses
Course of the Month16 days, 2 hours left to enroll

850 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