タグを削除したり 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 または purifier を使用してタグを閉じると、クリーンな HTML が出力されますが、HTML の 100 文字は表示されません。
$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>...";
類似の質問