PHP Remove Text Between [ and ] Parentheses

php, regex, string

Solution

You just need to remove everything between `[]` with the `preg_replace` function.

$a = 'hello, [how][are] you';

echo preg_replace('#\s*\[.+\]\s*#U', ' ', $a); // hello, you

The regex catches every spaces before and after and replace it with a single space.

Be careful, `[` and `]` are reserved characters in regex, you need to escape them with `\`. If you want to keep the possibility to write `[]` in your string (without anything between), you can transform the `.*` in `.+`.

Problem

I need to remove text included between [ and ] parentheses (and parentheses, too). For example: Hello, [how are you] Must become: Hello, And, a string like: hello, [how][are] you must become: hello, you There is a regula expression to do that?

Original source