Reputation: 101
The code below works perfectly:
$string = '(test1)';
$new = preg_replace('/^\(+.+\)+$/','word',$string);
echo $new;
Output:
word
If the code is this:
$string = '(test1) (test2) (test3)';
How to generate output:
word word word
?
Upvotes: 2
Views: 265
Reputation: 37755
Why my regex do not work ?
^ and $
are anchors which means match should start from start of string and expand upto end of string
.
means match anything except newline, +
means one or more, by default regex is greedy in nature so it tries to match as much as possible where as we want to match ( )
so we need to change the pattern a bit
You can use
\([^)]+\)
$string = '(test1) (test2) (test3)';
$new = preg_replace('/\([^)]+\)/','word',$string);
echo $new;
Upvotes: 1