Я бы использовал два индекса сложения: startOfValidArea и endOf ...
область - это где находится ваш текст, а индексы - где вы должны поместить свои теги <p...>
и </p>
или любые другие теги
Затем вы перемещаете эти теги, как:
startof .. установить окончание корня <div>
и найти первый случай <
после него, это первая область
и затем, пока вы не в конце, получите тег после упомянутой <
(например, подстрока между <
и ' '
или >
) и создайте временный конечный тег этого (например, </xxx>
), конечно знать о нескольких одинаковых тегах внутри (например, <table><table></table></table>
)
найдите этот временный конечный тег, и это будет следующий индекс startOf ..., снова найдите следующий <
, это вторая область и т. д.
надеюсь, что это ясно и понятно ..
Постскриптум знать о таких тегах, как <br />
, и проверять каждый запуск <
на эту ситуацию
это просто алгоритм, я не кодирую в php, но он должен быть похож на
Редактировать: код, но я не уверен, что он работает, у меня нет локального сервера для тестирования, надеюсь, это будет полезно
$textStart = stripos($postMessage, '>')+1; // startig index for the text to highlight
$textEnd = stripos($postMessage, '<', $textStartPos); // ending index for the text to highlight
while($textStart != false && $textEnd != false){
// while there is still any text to highlight
// insert the highlighting code
$postMessage = substr ($postMessage, 0, $textStart) . '<p class=\"postMessage\">' . substr ($postMessage, $textStart, $textEnd) . '</p>' . substr ($postMessage, $textEnd, strlen($postMessage);
// get the tag
$endOfTag = (stripos($postMessage, ' ', $textEnd) < stripos($postMessage, '>', $textEnd)) ? stripos($postMessage, ' ', $textEnd) : stripos($postMessage, '>', $textEnd);
$tag = substr ($postMessage, $textEnd, $endOfTag); // getting the tag here
if($tag == '<br' || $tag == '<img'){
// do smthing with not-paired tag, like check if the tag is ending with the '/>' string and then ignore it and get the next tag
}
$closingTag = '</'.substr($tag,1,strlen($tag)); // creating the closing tag like </div or </p
$nextSameTag = stripos($postMessage, $tag, $endTag);
$nextClosingTag = stripos($postMessage, $closingTag, $nextSameTag);
// loop through the same inner tags like <div>text<div>text</div>text</div>
while($nextSameTag < $nextClosingTag && $textStart != false && $textEnd != false){
$nextSameTag = stripos($postMessage, $tag, $nextClosingTag);
$nextClosingTag = stripos($postMessage, $closingTag, $nextSameTag);
}
$textStart = stripos($postMessage, '>', $nextClosingTag)+1;
$textEnd = stripos($postMessage, '<', $nextClosingTag);
}