Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Remove Text Between [ and ] Parentheses

Tags:

string

regex

php

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?

like image 671
Samuel Benares Avatar asked Dec 27 '13 17:12

Samuel Benares


Video Answer


1 Answers

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 .+.

like image 68
Maxime Lorant Avatar answered Sep 30 '22 16:09

Maxime Lorant