Created
April 26, 2012 08:46
-
-
Save TheDistantSea/2497743 to your computer and use it in GitHub Desktop.
Truncate a string up to a certain length, preserving whole words
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 | |
function str_truncate($str, $limit, $ellipsis = '...') { | |
if (strlen($str) <= $limit) { | |
return $str; | |
} | |
$limit -= strlen($ellipsis); | |
$pos = strrpos($str, ' ', $limit - strlen($str)); | |
if ($pos === false) { | |
$pos = $limit; | |
} | |
return substr($str, 0, $pos).$ellipsis; | |
} | |
function str_truncate2($str, $limit, $ellipsis = '...') { | |
$limit -= strlen($ellipsis); | |
return rtrim(preg_replace("/^(.{0,$limit})\\b.*/", '$1', $str)).$ellipsis; | |
} |
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 | |
include("str_truncate.php"); | |
$string = "the quick brown fox jumps over the lazy dog"; | |
for($limit = 10; $limit <= strlen($string); $limit += 10) { | |
print_r(str_truncate($string, $limit)); | |
} | |
for($limit = 10; $limit <= strlen($string); $limit += 10) { | |
print_r(str_truncate2($string, $limit)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment