Jefferson
Jefferson

Reputation: 101

Replace all occurrences using preg_replace

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

Answers (1)

Code Maniac
Code Maniac

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

\([^)]+\)

enter image description here


$string = '(test1) (test2) (test3)';
$new = preg_replace('/\([^)]+\)/','word',$string);
echo $new;

Regex Demo

Upvotes: 1

Related Questions