tags:

views:

1132

answers:

3

Hi, I have an array with some info.. for example:

"(writer) &"

or

"with (additional dialogue)".

I want to clean this so I only get the text between the parenthesis () and clear everything else

result:

"writer"

or

"additional dialogue"

how can I do this??

Thanks!!

+4  A: 

The easiest way will be with a regular expression:

preg_match_all('/\((.*?)\)/', $input, $matches);

$matches[1], $matches[2], etc will contain everything that was between parentheses in $input. That is, $matches[1] will have whatever was between the first set of parentheses, and so on (to handle cases with multiple sets).

Chad Birch
"The easiest way will be with a regular expression:" ...not if you want the parenthesis to balance! How do you think the OP wants to process "this (is (a) test)"? Your regex matches that as "is (a". Also, it's faster (I think) to do /[^)]*\)/ than to do /.*?/ to get text between parenthesis.
Chris Lutz
If he had specified that there could be nested parentheses I wouldn't have suggested regex. But he seems to be dealing with pretty simple input overall. Writing a parser when a one-line regex will do the same job is overkill.
Chad Birch
+1  A: 
$matches = array();
$num_matched = preg_match_all('/\((.*)\)/U', $input, $matches);
vartec
+3  A: 
$string = "this (is (a) test) with (two parenthesis) duh";

For a string like this you can use preg_match_all and use implode.

$string = "this (is (a) test) with (two parenthesis) duh";
$regex = '#\((([^()]+|(?R))*)\)#';
if (preg_match_all($regex, $string ,$matches)) {
    echo implode(' ', $matches[1]);
} else {
    //no parenthesis
    echo $string;
}

Or you can use preg_replace, but with multiple parenthesis you'll lose the whitespace between them.

$regex = '#[^()]*\((([^()]+|(?R))*)\)[^()]*#';
$replacement = '\1';
echo preg_replace($regex, $replacement, $string);

I got a lot of help from this page, Finer points of PHP regular expressions.

OIS
Interesting, I didn't know that PHP supported recursive regular expressions.
Chad Birch
Also assertions, backreferences and conditions. You can read it here: http://php.net/manual/en/regexp.reference.php#regexp.reference.back-references
OIS