删除括号外的文本

时间:2011-03-13 23:34:48

标签: php regex preg-replace

$text = 'remove this text (keep this text and 123)';

echo preg_replace('', '', $text);

应输出:

(keep this text and 123)

3 个答案:

答案 0 :(得分:5)

这样做:(并与嵌套的()一起使用)

$re = '/[^()]*+(\((?:[^()]++|(?1))*\))[^()]*+/';
$text = preg_replace($re, '$1', $text);

以下是几个测试用例:

Input:
Non-nested case: 'remove1 (keep1) remove2 (keep2) remove3'
Nested case:     'remove1 ((keep1) keep2 (keep3)) remove2'

Output:
Non-nested case: '(keep1)(keep2)'
Nested case:     '(keep1) keep2 (keep3)'

答案 1 :(得分:2)

在括号内找到任何内容,将其放入捕获组并仅保留,如下所示:

echo preg_replace('/^.*(\(.*\)).*$/', '$1', $text);

答案 2 :(得分:1)

这里是'non preg_replace'方式:

<?

$text = 'remove this text (keep this text)' ;

$start = strpos($text,"(") ; 
$end = strpos($text,")") ; 

echo substr($text,$start+1,$end-$start-1) ; // without brackets
echo substr($text,$start,$end-$start+1) ; // brackets included

?>

注意:
- 这只提取第一对括号 - 用strrpos()替换strpos()以获得最后一对括号 - 嵌套括号会造成麻烦。