开发者

Regular expression to remove second couple of parenthesis (only when available)

I have something like this:

$arr[] = 'Seto Hakashima'
$arr[] = 'Anna (segment "Yvan Attal") (as Robin Wright Penn)'
$开发者_JS百科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!


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.


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜