php - Shorten sentence and find nearest dot -
i'm writing blog , need function shows excerpt of post. i'm using substring checking if text longer 503 chars.
but cuts text in middle of word , in middle of html tag rest of page tag half written.
i.e: "text text text <strong>another piece of te [...]
, rest of page strong till hits new strong-end tag.
i tried removing elements post un-formats text.
how go in order "ok, text 980 chars, cut @ 503+whatever else needed last dot (.) or complete tag.
follows current code:
<?php $testo_preview = preg_replace("/<img[^>]+\>/i", ' ', $valore->testo); $testo_preview = preg_replace("/<a[^>]+>/i", '<a>', $testo_preview); $testo_preview = preg_replace("/<span[^>]+>/i", '<span>', $testo_preview); $testo_preview = preg_replace("/<div[^>]+>/i", '', $testo_preview); $testo_preview = str_replace("</div>", '', $testo_preview); $testo_preview = str_replace("\n", '<br>', $testo_preview); ?> <?php if(strlen($testo_preview) >= 503): ?> <?= substr($testo_preview, 0, 503).' [...]' ?> <?php else: ?> <?= $testo_preview; ?> <?php endif; ?>
edit:
i found pawel answer working ok, "gets point"...
i had change new domdocument() part messing html accents (in italian use accents , needed them stay). turn function taking part of code tigger, therefore upvoted both of you. came easy function:
function cleancut($cutat, $str){ $next_dot = strpos($str, '.', $cutat); if ($next_dot !== false){ // text after default cutoff contains dot need extend cutoff $preview_text = substr($str, 0, $next_dot + 1); // html cleanup $preview_text = strip_tags($preview_text); $preview_text = str_replace("\n", '<br>', $preview_text); } else { $preview_text = $str; } return $preview_text; }
it works fine , good. doesn't point (when there long link) can fine. see function tried replace \n
<br>
tag want, doesn't work. idea on why?
this function cut string cleanly @ point or after , remove html tags well. …
html code '...' single character.
// strips html tags , return clean word cut @ point // or after it. function cleancut($cutat, $str) { $tmp = strip_tags($str); $tmp = explode(' ',$tmp); foreach($tmp $k => $v) { $cleanstr .= $v.' '; if (strlen($cleanstr) >= $cutat) { return trim($cleanstr).'…'; } } // , case short string return $cleanstr; }
Comments
Post a Comment