2007 / June 22nd/ Truncate with fashion
One of my biggest pet peeves is lazy-truncating around the web. With a couple of lines of PHP and a little bit of substr love, you can cut down long sentences to a given number of characters like so:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod temp…
But for me, that’s not good enough. I like my truncating to follow the English language — which doesn’t cut off in the middle of words. Cutting off in the middle of words can also have some unexpected consequences when using markup like HTML, Markdown or Textile. Consider the following cut-off:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod **temp…
If you were using Markdown, this would make all the following text in the document bolded — yikes! What we need to do is do the following:
- Trim the string based off a given splitter — like a space (word) or a period (sentence).
- Apply any markup language (Markdown, etc)
- Balance any unbalanced tags (like
<strong>)
Here’s the snippet I use to do this, assuming you are running WordPress (for the balanceTags function) and Markdown (for the Markdown function).
// truncates a sentence (nicely) with markdown & balanced tags
// defaults to period separation
function truncate($string, $limit, $break=".", $pad="...") {
if(strlen($string) <= $limit) return $string;
if(false !== ($breakpoint = strpos($string, $break, $limit))) {
if($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return balanceTags(Markdown($string), true);
}
You’ll notice you can send in parameters of the limit, what character to use to break it up (period by default) and what to put after the truncated part (if there is any).
Now go off and make your truncations English-friendly!
1 Comment
Make a Comment
don’t be afraid, it’s just text

Warpspire is the place that web professional Kyle Neath writes about the web. 


July 8th | #
Kyle - This is great, I never thought of any different ways to truncate, this is my new method. thanks.