Categorized | News

Summary Function for Cropping Sentences

Posted on 07 August 2002 by Demian Turner

function by David Speake

The function CropSentence() takes 3 arguments: 1. the string to be cropped, 2. desired string length, 3. string to represent \’click for more\’, usually \’…\’

The function finds the last word that will fit into the specified maximum length, and returns the string that has been cropped.

The function makes sure that the last word is not cut in half.

Bookmark and Share

3 Comments For This Post

  1. oshkosh1966 Says:

    I think that you are making this too hard. I wrote a similar function and my logic went like this.
    – Check is sentence is longer than the max length (like yours)
    – If so, then find the last space in the sentence, using the strrpos function.
    – Cut off everything after the space and replace with whatever. I used the substr function.

    No loops or anything.

    Hope this helps.

  2. demian Says:

    agreed 🙂

  3. dspeake Says:

    This function was an adaptation of an ASP function, and thus the structure is similar to that.

    Below is a straight-forward and fast version for those that want to use such a function.

    	function cropsentence($txt='', $length=30, $trail='...')
    		$tmp = substr($txt, 0, $length);
    		$pos = strrpos($tmp, ' ');
    		$txt = substr($tmp, 0, $pos);
    		return $txt;

    :: David Speake
    :: – simply breaks

Leave a Reply



Demian Turner's currently-reading book recommendations, reviews, favorite quotes, book clubs, book trivia, book lists



PHPkitchen recommends you also check out the following sites :

Accounting for Small Businesses

FreeAgent sign-up