Answer the question
In order to leave comments, you need to log in
How to replace strings one by one with unique values using regular expressions?
Tell me how you can implement this:
there is a line
<p>text<p>
Answer the question
In order to leave comments, you need to log in
$str = '< p > text </p>';
$count = 0;
$str = preg_replace_callback('/< ?\/?\w+ ?\>/', function() use(&$count) {
$count++;
return "#p$count";
}, $str);
$str = '< p > text </p> <b> fdsgdfsg</b> <p>???</p> <div>hello, world!!< /div>';
$count = [];
$str = preg_replace_callback('/< ?\/?(\w+) ?\>/', function($matches) use(&$count) {
$key = $matches[1];
$count[$key] = isset($count[$key]) ? $count[$key] + 1 : 1;
return "#$key$count[$key]";
}, $str);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question