我有多个HTML字符串需要截取到100个字符(剥离内容而不是原始内容),而不剥离标签并且不破坏HTML。
原始HTML字符串(288个字符):
I have various HTML strings to cut to 100 characters (of the stripped content, not the original) without stripping tags and without breaking HTML.
$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>...";
类似的问题