7

I want to remove everything inside braces. For example, if string is:

[hi] helloz [hello] (hi) {jhihi}

then, I want the output to be only helloz.

I am using the following code, however it seems to me that there should be a better way of doing it, is there?

$name = "[hi] helloz [hello] (hi) {jhihi}";
$new  =  preg_replace("/\([^)]+\)/","",$name); 
$new = preg_replace('/\[.*\]/', '', $new);  
$new = preg_replace('/\{.*\}/', '', $new);  
echo $new;
double-beep
  • 5,031
  • 17
  • 33
  • 41
Vishnu
  • 2,372
  • 6
  • 36
  • 58

2 Answers2

21

This should work:

$name = "[hi] helloz [hello] (hi) {jhihi}";
echo preg_replace('/[\[{\(].*?[\]}\)]/' , '', $name);

Paste it somewhere like: http://writecodeonline.com/php/ to see it work.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Damien Overeem
  • 4,487
  • 4
  • 36
  • 55
  • 2
    you will have problem if you have another closing brace inside one of the braces something like this `$name = "[h)i] helloz [hello] (hi) {jhihi}";` – bansi Nov 13 '13 at 08:28
  • 1
    Yep, but that wasn't one of the options so I didn't take it into consideration. No need to make things harder then they need to be. – Damien Overeem Nov 13 '13 at 08:31
  • 1
    @DamienOvereem no worries (i agree), I just cautioned the OP not to get into problems later. – bansi Nov 13 '13 at 08:32
3

[old answer]

If needed, the pattern that can deal with nested parenthesis and square or curly brackets:

$pattern = '~(?:(\()|(\[)|(\{))(?(1)(?>[^()]++|(?R))*\))(?(2)(?>[^][]++|(?R))*\])(?(3)(?>[^{}]++|(?R))*\})~';

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

[EDIT]

A pattern that only removes well balanced parts and that takes in account the three kinds of brackets:

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

This pattern works well but the additional type check is a bit overkill when the goal is only to remove bracket parts in a string. However it can be used as a subpattern to check if all kind of brackets are balanced in a string.


A pattern that removes only well balanced parts, but this time, only the outermost type of bracket is taken in account, other types of brackets inside are ignored (same behavior than the old answer but more efficient and without the useless conditional tests):

$pattern = '~
    \[ ( [^][]*+ (?: \[ (?1) ] [^][]* )*+ )  ]
  |
    \( ( [^)(]*+ (?: \( (?2) ] [^)(]* )*+ ) \)
  |
     { ( [^}{]*+ (?:  { (?3) } [^}{]* )*+ )  }
~xS';
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125