Reputation: 301
I have this content "Lorem ipsum dolor sit amet,[Hello world] consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis."
I want to remove any thing wrap by []
so the result of this content should be removed [Hello world]
Like this
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.
Upvotes: 0
Views: 90
Reputation: 39704
Use preg_replace:
$string = 'Lorem ipsum dolor sit amet,[Hello world] consectetur adipiscing elit. Mauris ornare luctus diam sit amet mollis.';
$newString = preg_replace('/\[.+?\]/', '', $string);
echo $newString;
Upvotes: 4
Reputation: 1776
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.
\
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.
Upvotes: 0