$item = "(1) Robin Hood (hero)";
Text inside brackets can be changed.
How do I remove all the brackets with text inside them from the string?
We should get this:
$item = "Robin Hood";
You can use preg_replace
as:
$item = preg_replace('/\(.*?\)/s','',$item);
Looks like you also want to remove leading and trailing spaces after the replacement.
You can make use of trim
for that as:
$item = trim( preg_replace('/\(.*?\)/s','',$item));
The regex used is \(.*?\)
:
(
and )
are regex meta-characters
used for grouping. To match literal
paranthesis you need to escape them
by preceding them with a \
..*?
. You
could also do the same using [^)]*
.
by default does not match a
newline. To make is match a newline
we use the s
modifier. Without it
we would fail to do the replacement
in "(hello\nworld) Hi"