我有各种 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's 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... */
剥离的 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>...";
类似问题