PHP function to get limited words from string words_limit()

Sometimes you want to get limited words from a string to make a clean or search engine friendly meta description of 255 words. 

Here is small php function to do this task easily. In this function there are 3 parameters string, limit and suffix to add three (...) dots or anything. 

Source Code:

<?php

function words_limit($string, $limit, $suffix = '...'){
    $words = explode(" ",$string);
    $string = implode(" ",array_splice($words,0,$word_limit));
    return $string.$suffix;
}


Output / Usage:

$text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.";

$start = limit_words($text,50);

Comments: (Your feedback is valuable to us)

David 1 year ago Reply

A simple and inlleeigtnt point, well made. Thanks!

Davinder Singh 1 year ago

thanks :)