Delete text outside brackets

i.e.

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

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

It should output:

(keep this text and 123)
+3
source share
3 answers

Take something found in brackets, put it in a capture group and save only this:

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

This will be done: (and works with nested ())

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

Here are some 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)'
+5
source

Here is the path "not 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

?>

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

+1
source

All Articles