user317005
user317005

Reputation:

Remove the text outside the brackets

i.e.

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

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

It should output:

(keep this text and 123)

Upvotes: 3

Views: 3159

Answers (3)

Anne
Anne

Reputation: 27073

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.

Upvotes: 1

ridgerunner
ridgerunner

Reputation: 34385

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

Upvotes: 7

BoltClock
BoltClock

Reputation: 723388

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

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

Upvotes: 2

Related Questions