I
I
Ivan Petrov2018-04-12 17:28:36
PHP
Ivan Petrov, 2018-04-12 17:28:36

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>

I need to alternately, using regular expressions, replace the tags with unique strings.
for example, the function receives: < p > text < /p >
the function returns: #p1 text #p2

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-04-12
@bitande

$str = '< p > text </p>';

$count = 0;
$str = preg_replace_callback('/< ?\/?\w+ ?\>/', function() use(&$count) {
  $count++;
  return "#p$count";
}, $str);

or if different tags need to be replaced independently
$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);

N
Nick Sdk, 2018-04-12
@lidacriss

like this?
sandbox.onlinephpfunctions.com/code/1abc6598e505ca...
or so
sandbox.onlinephpfunctions.com/code/1b9b94e3a7a1e8...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question