substr replacement that does not break words

function snippet($text,$length=64,$tail="...") {
    $text = trim($text);
    $txtl = strlen($text);
    if($txtl > $length) {
        for($i=1;$text[$length-$i]!=" ";$i++) {
            if($i == $length) {
                return substr($text,0,$length) . $tail;
            }
        }
        $text = substr($text,0,$length-$i+1) . $tail;
    }
    return $text;
}
 

Download this snippet

This PHP function shortens a string without breaking words.

Twitter Twitter

5 Comments to “ substr replacement that does not break words”

  1. Anonymous  on Sep 25, 2009

    xieBbj <a href="http://jzmxnuwrgkql.com/">jzmxnuwrgkql</a>, [url=http://upxxfcbsmpqm.com/]upxxfcbsmpqm[/url], [link=http://ccqczijlvqiw.com/]ccqczijlvqiw[/link], http://bqipylacifsy.com/

  2. Anonymous  on Nov 04, 2009

    gRDaWR <a href="http://dkrbbuukuywn.com/">dkrbbuukuywn</a>, [url=http://pbkhrgmcekzm.com/]pbkhrgmcekzm[/url], [link=http://jirajzkrlprm.com/]jirajzkrlprm[/link], http://lmxypprjkszw.com/

  3. Anonymous  on Jan 13, 2010

    v9WNKG <a href="http://rcxajobzpxqt.com/">rcxajobzpxqt</a>, [url=http://akwbutdcaznv.com/]akwbutdcaznv[/url], [link=http://cxzbgyucyijs.com/]cxzbgyucyijs[/link], http://otnobgaskjeu.com/

  4. Anonymous  on Jan 22, 2010

    qUbKKj <a href="http://mpekufddyxqa.com/">mpekufddyxqa</a>, [url=http://ntpqutgncnsm.com/]ntpqutgncnsm[/url], [link=http://mqtszjhwfslr.com/]mqtszjhwfslr[/link], http://lgnfaffjjuaj.com/

  5. Anonymous  on Mar 14, 2010

    bxnTXh <a href="http://hyijwjjwnxzy.com/">hyijwjjwnxzy</a>, [url=http://ryllceinajic.com/]ryllceinajic[/url], [link=http://vygftswotvvd.com/]vygftswotvvd[/link], http://tpbbnzpoevko.com/

Leave a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>