Reputation: 59
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?
Upvotes: 5
Views: 5153
Reputation: 89639
You can use this if you want to deal with nested brackets and extra horizontal whitespaces:
$txt = preg_replace('~\h*\[(?:[^][]+|(?R))*+]\h*~', ' ', $txt);
or with an unrolled loop:
$txt = preg_replace('~\h*\[[^][]*+(?:(?R)[^][]*)*+]\h*~', ' ', $txt);
Upvotes: 3
Reputation: 7948
use this pattern \[.*?\](?![^\[\]]*\])
to handle nesting as well Demo
Upvotes: 0
Reputation: 39443
what about this?
print preg_replace('/\[[^\[\]]*\]/', '', $str);
Upvotes: 0
Reputation: 36181
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 .+
.
Upvotes: 7