How to replace everything between {} [] () braces from a string?

15,246

Solution 1

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.

Solution 2

[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';
Share:
15,246
Vishnu
Author by

Vishnu

I am creator of and torrent search engine

Updated on June 15, 2022

Comments

  • Vishnu
    Vishnu almost 2 years

    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;