I'm aware of various ways to truncate an HTML string to a certain length including/not including the HTML tags as part of the result and/or truncating while preserving whole words and whatnot. My issue, though, is if the string includes special characters such as –
or &
I need to truncate a string to 100 characters (or a few less if it would otherwise truncate in the middle of a special character). Right now I have a function:
$result= truncateIfNecessary(strip_tags($fullText), 100); //ignore HTML tags
function truncateIfNecessary($string, $length) {
if(strlen($string) > $length) {
return substr($string, 0, $length).'...';
} else {
return $string;
}
}
But if the string is something like text text – text
(displayed on the page as: text text - text
and $length
falls in –
, it returns text text &nda...
which displays exactly like that, when I would need it to return text text...
.
EDIT:
(posted as answer)