Skip to content

Instantly share code, notes, and snippets.

@dev-jaydeep
Created November 24, 2020 08:14
Show Gist options
  • Save dev-jaydeep/b4e19f7fb2d2cf37c616bfb223872078 to your computer and use it in GitHub Desktop.
Save dev-jaydeep/b4e19f7fb2d2cf37c616bfb223872078 to your computer and use it in GitHub Desktop.
Ellipsize String
/**
* Ellipsize String
*
* This function will strip tags from a string, split it at its max_length and ellipsize
*
* @param string string to ellipsize
* @param int max length of string
* @param mixed int (1|0) or float, .5, .2, etc for position to split
* @param string ellipsis ; Default '...'
* @return string ellipsized string
*/
function _ellipsize($str, $max_length, $position = 1, $ellipsis = '…') {
// Strip tags
$str = trim(strip_tags($str));
// Is the string long enough to ellipsize?
if (mb_strlen($str) <= $max_length) {
return $str;
}
$beg = mb_substr($str, 0, floor($max_length * $position));
$position = ($position > 1) ? 1 : $position;
if ($position === 1) {
$end = mb_substr($str, 0, -($max_length - mb_strlen($beg)));
} else {
$end = mb_substr($str, -($max_length - mb_strlen($beg)));
}
return $beg . $ellipsis . $end;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment