phpregexreplacesanitizationbrackets

Remove a square braced expression from a string


I am trying to delete [] parentheses with whats inside of them from string in php.

Input: Hello [string] world!

Expected output: Hello world!

What I tried is:

ereg_replace("\[[^\]]*\]","",$sres);

Where $sres is the string I am trying to clean up. This should work imo and for some weird reason it does little bit. It actually replaces "[1]" with "", but it does not replace for example "[edit]", nor "[""]" and so on. I even tried to wrap the regex in / / :

ereg_replace("/\[[^\]]*\]/","",$sres);

But this didn't work at all, not even on that "[1]".


Solution

  • You could use preg_replace.

    preg_replace('~\[[^\]]*\]~', '', $sres);
    

    DEMO