我有这样的事情:
$arr[] = 'Seto Hakashima'
$arr[] = 'Anna (segment "Yvan Attal") (as Robin Wright Penn)'
$arr[] = 'Sara (segment "Yvan Attal")'
我需要删除第二对括号(仅当有第二对时),并得到这个:
$arr[] = 'Seto Hakashima'
$arr[] = 'Anna (segment "Yvan Attal")'
$arr[] = 'Sara (segment "Yvan Attal")'
谢谢!
答案 0 :(得分:1)
尝试
preg_replace('/^([^(]+(?:\([^)]+\))?).*/','$1', $item);
几点解释
^ - start of the string
[^(]+ - match characters before first bracket
\([^)]+\) - match first bracket
(?: ... )? - optional
.* - eat the rest
$1 - replace with match string
或者只删除最后一部分
preg_replace('/(?<=\))\s*\(.*$/','', $item);
(?<=\)) - if there is ) before pattern
(\s*\(.*$ - remove everything after `(` and also zero or more whitespaces before last bracket.
答案 1 :(得分:1)
这有效:
<?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";
}
输出:
Seto Hakashima
Anna(段“Yvan Attal”)
Sara(段“Yvan Attal”)
Anna(段“Yvan Attal”)第二组之后的奖励文本
正如你在上一个例子中所注意到的,这个正则表达式足够具体,它只消除了第二组括号,并保持了其余的字符串。