Skip to content

Instantly share code, notes, and snippets.

@TheDistantSea
Created April 26, 2012 08:46
Show Gist options
  • Save TheDistantSea/2497743 to your computer and use it in GitHub Desktop.
Save TheDistantSea/2497743 to your computer and use it in GitHub Desktop.
Truncate a string up to a certain length, preserving whole words
<?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;
}
<?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