tags:

views:

51

answers:

2

Hi, I have something like this:

$arr[] = 'Seto Hakashima'
$arr[] = 'Anna (segment "Yvan Attal") (as Robin Wright Penn)'
$arr[] = 'Sara (segment "Yvan Attal")'

I need to remove the the second couple of parenthesis (only when there is a second couple), and get this:

$arr[] = 'Seto Hakashima'
$arr[] = 'Anna (segment "Yvan Attal")'
$arr[] = 'Sara (segment "Yvan Attal")'

Thanks!

+1  A: 

Try

preg_replace('/^([^(]+(?:\([^)]+\))?).*/','$1', $item);

Few explanations

^          - start of the string
[^(]+      - match characters before first bracket
\([^)]+\)  - match first bracket
(?: ... )? - optional
.*         - eat the rest
$1         - replace with match string

Or just remove last part

preg_replace('/(?<=\))\s*\(.*$/','', $item);

(?<=\))    - if there is ) before pattern
(\s*\(.*$  - remove everything after `(` and also zero or more whitespaces before last bracket.
S.Mark
doesn't remove " (as Robin Wright Penn)"
ax
problem when there are parenthesis inside parenthesis..
Jonathan
yeah, parenthesis inside parenthesis does not support that.
S.Mark
+1  A: 

This works:

<?php
$arr[] = 'Seto Hakashima';
$arr[] = 'Anna (segment "Yvan Attal") (as Robin Wright Penn)';
$arr[] = 'Sara (segment "Yvan Attal")';
$arr[] = 'Anna (segment "Yvan Attal") (as Robin Wright Penn) BONUS text after second group';

foreach ($arr as $item) {
    print preg_replace('/(\([^\)]*\)[^\(]+)\([^\)]*\)\s*/','$1',$item) . "\n";
}

Output:

Seto Hakashima

Anna (segment "Yvan Attal")

Sara (segment "Yvan Attal")

Anna (segment "Yvan Attal") BONUS text after second group

As you'll notice in the last example, this regex is specific enough that it eliminates only the second group of parenthesis and keeps the rest of the string in tact.

Matt
Thanks.. seems to be working good also with parenthesis inside parenthesis..
Jonathan