www.friend0.in
www.friend0.in

Reputation: 257

Remove text outside of [] {} () bracket

I have a string, from which I want to keep text inside a pair of brackets and remove everything outside of the brackets:

Hello [123] {45} world (67)
Hello There (8) [9] {0}

Desired output:
[123] {45} (67) (8) [9] {0}

Code tried but fails:

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

Upvotes: 3

Views: 2018

Answers (3)

bobble bubble
bobble bubble

Reputation: 18565

Looks like you wanted to target nested stuff as well. There are already questions about how to match balanced parenthesis. Adjust one of those patterns to fit your needs, e.g. something like

$pattern = '/\((?:[^)(]*(?R)?)*+\)|\{(?:[^}{]*+(?R)?)*\}|\[(?:[^][]*+(?R)?)*\]/';

You can try this on Regex101. Extract those with preg_match_all and implode the matches.

if(preg_match_all($pattern, $str, $out) > 0)
  echo implode(' ', $out[0]);

If you need to match the stuff outside, even with this pattern you can use (*SKIP)(*F) that also used @Thefourthbird in his elaborately answer! For skipping the bracketed see this other demo.

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163642

If the values in the string are always an opening bracket paired up with a closing bracket and no nested parts, you can match all the bracket pairs which you want to keep, and match all other character except the brackets that you want to remove.

(?:\[[^][]*]|\([^()]*\)|{[^{}]*})(*SKIP)(*F)|[^][(){}]+

Explanation

Regex demo | Php demo

Example code

$re = '/(?:\[[^][]*]|\([^()]*\)|{[^{}]*})(*SKIP)(*F)|[^][(){}]+/m';
$str = 'Hello [123] {45} world (67)
Hello There (8) [9] {0}';

$result = preg_replace($re, '', $str);

echo $result;

Output

[123]{45}(67)(8)[9]{0}

If you want to remove all other values:

(?:\[[^][]*]|\([^()]*\)|{[^{}]*})(*SKIP)(*F)|.

Regex demo

Upvotes: 5

41686d6564
41686d6564

Reputation: 19661

If the brackets are not nested, the following should suffice:

[^[{(\]})]+(?=[[{(]|$)

Demo.

Breakdown:

[^[{(\]})]+     # Match one or more characters except for opening/closing bracket chars.
(?=[[{(]|$)     # A positive Lookahead to ensure that the match is either followed by
                # an opening bracket char or is at the end of the string.

Upvotes: 1

Related Questions