使用 PHP substr() 和 strip_tags(),同时保留格式设置且不破坏 HTML
2022-08-30 11:08:58
我有各种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>...";
类似问题