Created
August 27, 2013 09:14
-
-
Save sepehr/6351409 to your computer and use it in GitHub Desktop.
PHP: truncate()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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