Solved

PHP Regexp for Nested Parentheses

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
change password links 7 74
php date - compare 4 40
mcrypt_create_iv() is deprecated 4 74
Regex PHP lines with newlines not being matched - all other match fine 4 23
Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
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 dynamically set the form action using jQuery.

920 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

15 Experts available now in Live!

Get 1:1 Help Now