Skip to content

Instantly share code, notes, and snippets.

@sepehr
Created August 27, 2013 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sepehr/6351409 to your computer and use it in GitHub Desktop.
Save sepehr/6351409 to your computer and use it in GitHub Desktop.
PHP: truncate()
<?php
/**
* Truncates string to the specified length.
*
* @param string $string String to truncate.
* @param integer $len Desired length.
* @param boolean $wordsafe Whether to truncate on word boundries or not.
* @param boolean $dots Whether to add dots or not.
*
* @return string
*/
function truncate($string, $len, $wordsafe = TRUE, $dots = TRUE)
{
if (mb_strlen($string) <= $len)
{
return $string;
}
$dots AND $len -= 4;
if ($wordsafe)
{
// Leave one more character
$string = mb_substr($string, 0, $len + 1);
// Space exists AND is not on position 0
if ($last_space = strrpos($string, ' '))
{
$string = substr($string, 0, $last_space);
}
else
{
$string = mb_substr($string, 0, $len);
}
}
else
{
$string = mb_substr($string, 0, $len);
}
// Add ellipsis
$dots AND $string .= ' ...';
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment