3

i.e.

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

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

It should output:

(keep this text and 123)

3 Answers3

7

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)'
ridgerunner
  • 33,777
  • 5
  • 57
  • 69
  • 1
    @David Thomas: I don't think the comment should be there to begin with. The block *should* highlight as PHP by default. – BoltClock Mar 13 '11 at 23:50
  • @BoltClock thanks! I'd tried to roll it back to before I started messing with it (because despite the preview the code wasn't being *shown* as code). But got stuck :( – David Thomas Mar 14 '11 at 00:02
  • 1
    Regarding the highlighting... Its true that you don't need the comment, but this helps force a specific language See: [Manually specify language for syntax highlighting](http://meta.stackexchange.com/questions/78363/manually-specify-language-for-syntax-highlighting/81971#81971) – ridgerunner Mar 14 '11 at 00:18
2

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

echo preg_replace('/^.*(\(.*\)).*$/', '$1', $text);
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • The regex: `/^.*(\(.*\)).*$/` does not work if there is more than one set of parentheses. e.g. it fails when you feed it this: `remove this text (keep this1) remove this too (keep this2)` – ridgerunner Mar 14 '11 at 00:13
1

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.

Anne
  • 26,765
  • 9
  • 65
  • 71
  • This solution does not work. It returns `'(keep this text'` (it does not include the closing parentheses). It also fails when there are more than one set of parens. – ridgerunner Mar 14 '11 at 00:50