<?php
$offsets = [
1 => [0,2],
2 => [2,5],
3 => [8,9]
];
$html = <<<HTML
<div>This is</div> only a test for stackoverflow
HTML;
$ignoreTag = false;
$insertTagStart = false;
$char = 0;
for ($i = 0; $i < strlen($html); ++$i) {
if ($ignoreTag && $html[$i] == '>') {
$ignoreTag = false;
} elseif ($html[$i] == '<') {
if ($insertTagStart !== false) { // insert tag interruption, print closing tag, modify the lookup
++$offsets[$insertTagStart][0];
$html = substr_replace($html, "</span>", $i, 0);
$i += 6; // </span> = 7 minus 1 before loop's increment
}
$ignoreTag = true;
} else {
foreach ($offsets as $id => $set) {
if ($char == $set[0]) {
$insertTagStart = $id;
$insertTag = "<span class='annotation n-{$id}'>";
$i += strlen($insertTag) - 1; // compensate for inserted substring while traversing html
$html = substr_replace($html, $insertTag, $char, 0);
} elseif ($insertTagStart == $id && $set[1] == $char) {
$html = substr_replace($html, "</span>", $char, 0);
$insertTagStart = false;
}
}
++$char;
}
echo "{$char},\t" ,
($ignoreTag ? 't' : 'f') , ",\t" ,
($insertTagStart === false ? 'f' : $insertTagStart) , ",\t" ,
$html , "\n";
}
echo $html;
preferences:
27.07 ms | 402 KiB | 5 Q