У меня есть различные строки HTML, чтобы вырезать до 100 символов (отделяемого контента, а не оригинала) без удаления тегов и без нарушения HTML.
Оригинальная строка HTML (288 символов):
$content = "<div>With a <span class='spanClass'>span over here</span> and a
<div class='divClass'>nested div over <div class='nestedDivClass'>there</div>
</div> and a lot of other nested <strong><em>texts</em> and tags in the air
<span>everywhere</span>, it a HTML taggy kind of day.</strong></div>";
Стандартная обрезка: обрезать до 100 символов и разрывов HTML, разделенное содержимое доходит до ~ 40 символов:
$content = substr($content, 0, 100)."..."; /* output:
<div>With a <span class='spanClass'>span over here</span> and a
<div class='divClass'>nested div ove... */
Stripped HTML: выводит правильный счетчик символов, но явно теряет форматирование:
$content = substr(strip_tags($content)), 0, 100)."..."; /* output:
With a span over here and a nested div over there and a lot of other nested
texts and tags in the ai... */
Частичное решение: использование HTML Tidy или очистителя для закрытия тегов выводит чистый HTML, но не более 100 символов HTML не отображается.
$content = substr($content, 0, 100)."...";
$tidy = new tidy; $tidy->parseString($content); $tidy->cleanRepair(); /* output:
<div>With a <span class='spanClass'>span over here</span> and a
<div class='divClass'>nested div ove</div></div>... */
Задача: вывести чистые символы HTML и n (исключая количество символов HTML-элементов):
$content = cutHTML($content, 100); /* output:
<div>With a <span class='spanClass'>span over here</span> and a
<div class='divClass'>nested div over <div class='nestedDivClass'>there</div>
</div> and a lot of other nested <strong><em>texts</em> and tags in the
ai</strong></div>...";
Похожие вопросы