Words limiter function

Discussion in 'PHP' started by ruud, Jul 15, 2007.

  1. #1
    I'm looking for a function for limit the text to a number words.

    example : limitarticle(a a a as as sdasf asdad asdasd asdasdf asdasda, 4) = "a a a as"

    understand? :(

    sorry for my bad english
     
    ruud, Jul 15, 2007 IP
  2. Chemo

    Chemo Peon

    Messages:
    146
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
    /** 
     * Function to return break text and add "more" link
     * @author Bobby Easland 
     * @version 1.0
     * @param string $text Text to be broken
     * @param integer $limit Number of words to limit
     * @param string $more_link String to be added at end of return string
     * @return string
     */
    function breakText($text, $limit = 25, $more_link = '...'){
    	$container = explode(' ', ereg_replace("[[:space:]]+", ' ', $text));
    	$i = 0;
    	$words = array();
    	while ( (count($words) < $limit) && isset($container[$i]) ){
    		if ( !empty($container[$i]) ){
    			$words[] = $container[$i];
    			if (count($words) == $limit){
    				$words[] = $more_link;
    			} # end if
    		} # end if
    		unset($container[$i]);
    		$i++;
    	} # end while
    	return implode(' ', $words);
    } # end function
    
    PHP:
     
    Chemo, Jul 15, 2007 IP