Reputation: 257
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
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
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
(?:
Non capture gorup
\[[^][]*]
Match from [...]
|
Or\([^()]*\)
Match from (...)
|
Or{[^{}]*}
Match from {...}
)
Close non capture group(*SKIP)(*F)|
consume characters that you want to avoid, and that must not be a part of the match result[^][(){}]+
Match 1+ times any char other than 1 of the listedExample 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)|.
Upvotes: 5
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