CD and DVD movies available for download at download movies portal, cheap prices. If you are searching for mp3s, you could try to download mp3 music at this mp3 portal. Super quality, high speed downloads.

*

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:

  1. Trim the string based off a given splitter — like a space (word) or a period (sentence).
  2. Apply any markup language (Markdown, etc)
  3. 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!

A word from the sponsors. Advertise with Warpspire

1 Comment

comments feed

  1. Gravatar
    Joseph

    July 8th | #

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

Make a Comment

don’t be afraid, it’s just text

Comments are parsed with Markdown. Basic HTML is also allowed.