[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

Download this code from github


/**
 * @author: Tanveer Noman
 * @description: This function can limit word from any paragraph
 * @license http://opensource.org/licenses/mit-license.html MIT
 * @copyright (c) 2010, Tanveer Noman
 * @version 1.0
 * */


define("STRING_DELIMITER", " ");

/*
 * @params: String, Integer
 * @return: String
 */
function word_limiter($str, $limit = 10) {
    $str = strip_tags($str); // Updated from Ivan Dimov
    if (stripos($str, STRING_DELIMITER)) {
        $ex_str = explode(STRING_DELIMITER, $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



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

Advertisements

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.

19 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 ??

  8. dika says:

    this is very useful

    thank you very much

  9. avb says:

    Nice article! You helped me a lot!

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 )

Google+ photo

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

Connecting to %s