[PHP] Use word_limiter() function to limit your words

There is nice little tricks to make meaningful summary text form big description less than a sec? ;-)
This example can also be used to create more link in short description.
This Function will cut words from Text and displaying limited words

function word_limiter($str,$limit=10)
{
    if(stripos($str," ")){
    $ex_str = explode(" ",$str);
        if(count($ex_str)>$limit){
            for($i=0;$i<$limit;$i++){
            $str_s.=$ex_str[$i]." ";
            }
        return $str_s;
        }else{
        return $str;
        }
    }else{
    return $str;
    }
}

How does it work:
1. Define how many words you want to display.
2. Find what is the last character displaying.
3. If the last character displaying is not ” ” (Space) then again go next character until found.
4. Display words

<?php

/**
 * @example one
 */
echo word_limiter('Hellya!!! this function really works nice for me.',4)."...";
//this Returns "Hellya!!! this function really ..."
?>

About Tanveer
RIA (Rich Internet Application) Developer with a wide variety of business applications. Particularly interested in client/server and relational database design. Always interested in migration projects, as well as close interaction with the DB manufacturers.

12 Responses to [PHP] Use word_limiter() function to limit your words

  1. Md. Bahar Uddin says:

    Excellent!!!

  2. Sahbaj says:

    Ya, this good but what happened if there is HTML tag in description.

  3. Rumana says:

    Cool, Thanks to share

  4. Thanks!!! just what I need

  5. anand says:

    Thanks You for help this information is very help ful for me

  6. shahidkhan says:

    what about that string which dose not contain the spaces?

  7. Tanveer says:

    Why do you want to limit a long length string with this method ??

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 286 other followers