preg_replace is the way to go. It uses a regular expression to match a pattern in your input string (third parameter) and returns a string that replaces anything that matches the pattern (first parameter) with your replacement string (second parameter).
$input = "Lorem ipsum dolor sit amet,[Hello world] consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.";
$output = preg_replace('/\[.+\]/', '', $input);
echo $output;
Will give you:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.
- An important thing to realize in this case is that you need to use a
\
to escape the [
and ]
characters because they have special meaning in regular expressions. The Wikipedia entry on regular expressions has a section that goes over the syntax and covers other metacharacters.
Another consideration is that you should use +
for nongreedy matching instead of *
because if your input is:
$input = "Lorem ipsum dolor sit amet,[Hello world] consectetur [test] adipiscing elit. Mauris ornare luctus diam sit amet mollis.";
then your output will remove consectetur
which you probably don't want and give you:
Lorem ipsum dolor sit amet, adipiscing elit. Mauris ornare luctus diam sit amet mollis.
$output = preg_replace('#\[.+?\]#s', '', $input)
. – DCoder