Question:

How to get a trimmed article synopsis with PHP?

by Guest33847  |  earlier

0 LIKES UnLike

How do I specify that a post only show a certain amount of words in PHP, and then it shows a continuation link that will take my users to the full article? An example would be on wired.com. At the bottom, there is a tabbed section where the tabs say 'latest blog post,' 'most popular articles,' etc. Each post there only shows a specific amount of words and then there is an ellipses that indicates that the user may continue the article.

 Tags:

   Report

3 ANSWERS


  1. Unfortunately, Yahoo! will munge the formatting of this answer, but here it goes:

    <?php

    $limit = 50;

    $string = "How do I specify that a post only show a certain amount of words in PHP, and then it shows a continuation link that will take my users to the full article? An example would be on wired.com. At the bottom, there is a tabbed section where the tabs say 'latest blog post,' 'most popular articles,' etc. Each post there only shows a specific amount of words and then there is an ellipses that indicates that the user may continue the article.";

    $string = wordLimit($string, $limit);

    printf('<p>%s</p>', $string);

    function wordLimit($inputStr, $wordLimit) {

        

        // if the input isn't longer than the limit,

        // we have no work

        if (str_word_count($inputStr) <= $wordLimit)

            return $inputStr;

        

        $truncated = '';

        $token = strtok($inputStr, ' ');

        for ($i = 0; $token !== false && $i < $wordLimit; $token = strtok(' '), $i++) {

            if (strlen($token) > 0)

                $truncated .= $token . ' ';

        }    

        return rtrim($truncated) . '...';

    }

    ?>


  2. Look into substr(), where you can tell it to return say the first 100 characters.  Then concatinate a "..." to the end, build the link, and you're done.

  3. Check this link

    http://www.webdevboost.co.uk/Programming...

    The following function makes it really simple to create

    <?php

    function shorten($var_name,$var_length)

    {

    if(strlen($var_name) > $var_length)

    {

    return substr($var_name,0,$var_length-3)."...";

    }

    else

    {

    return $var_name;

    }

    }

    echo shorten ("This word will be shortened and a treble dot will be added",40);

    ?>

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.