Remove the text outside the brackets

2019-02-25 05:55发布

问题:

i.e.

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

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

It should output:

(keep this text and 123)

回答1:

Take anything found within the brackets, put it in a capture group and keep that only, like this:

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


回答2:

This will do it: (and works with nested () as well)

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

Here are a couple test cases:

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)'


回答3:

Here the 'non preg_replace' way:

<?

$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

?>

Note:
- This extracts only the first pair of brackets.
- Replace strpos() with of strrpos() to get the last pair of brackets.
- Nested brackets cause trouble.