Skip to content

Instantly share code, notes, and snippets.

@ofca-snippets
Created September 15, 2012 23:43
Show Gist options
  • Save ofca-snippets/3730373 to your computer and use it in GitHub Desktop.
Save ofca-snippets/3730373 to your computer and use it in GitHub Desktop.
[php] Extended version of substr.
/**
* Alternative version of substr function. This function
* cut a string to the word closest to a certain number
* of characters.
*
* @param string $text The input string.
* @param integer $chars_number Number of characters.
* @param boolean $watch_words Watch on words?
* @param boolean $end_dots Put three ending dots?
* @return string
*/
function cut($text, $chars_number = 100, $watch_words = TRUE, $end_dots = TRUE)
{
$dots = FALSE;
if ($end_dots AND strlen($text) > $chars_number)
{
$dots = TRUE;
}
if ($watch_words)
{
$text = strip_tags($text);
if (strlen($text) > $chars_number)
{
$pos = strpos($text, ' ', $chars_number);
if ($pos !== FALSE)
{
$text = substr($text, 0, $pos);
}
}
}
return $text . ($dots ? '...' : NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment