You have multiple goals, the simplest way to accomplish them imo is doing it step-by-step.
1. The RegEx
You want two HTML tags, these can be caught easily via /(<a|<div)/i
(explanation, g
modifier is only used to demonstrate that it correctly matches).
With this you could write the following code:
$parsed = preg_replace_callback('/(<a|<div)/i', ???, $string);
2. The callback
The logic behind this can be simplified to the following switch
switch ($found) {
case '<div':
$result = '<div id="b_'.$id.'"';
break;
case '<a':
$result = '<!-- UNIT'.$id.' --><a id="a_'.$id.'"';
break;
default:
$result = "";
break;
}
To implement this you can either write a new function or use an anonymous one. To make $id
accessible, you need to learn about variable scope in PHP. An easy way out of using anything like global $id;
or define()
is using Closures with the use()
syntax. To be able to manipulate $id
(increment it), you'll need to pass it by reference (when using Closures). This brings you to the following code:
$parsed = preg_replace_callback("/(<a|<div)/", function($match) use (&$id) {
switch ($match[1]) {
case '<div':
$result = '<div id="b_'.$id.'"';
break;
case '<a':
$result = '<!-- UNIT'.$id.' --><a id="a_'.$id.'"';
break;
default:
$result = $match[1];//do nothing
break;
}
$id++;
return $result;
}, $string);
Watch it work here.