April 29, 2012

PHP – Summary of article

Question by user1257255

I’m working on news script and I would like to create summary function to get little of text from full text content. The function would get 200 characters of full text and then it would search for last space of these 200 characters. The function must also ignore any html or other code and show only first 200 characters of full text content.

Which function is the best for my problem and how to do that function?

Answer by mazzucci

Checkout this helper function from the CodeIgniter framework:

/**
* Character Limiter
*
* Limits the string based on the character count.  Preserves complete words
* so the character count may not be exactly as specified.
*
* @access   public
* @param    string
* @param    integer
* @param    string  the end character. Usually an ellipsis
* @return   string
*/

function character_limiter($str, $n = 500, $end_char = '…')
{
    if (strlen($str) < $n)
    {
        return $str;
    }

    $str = preg_replace("/s+/", ' ', str_replace(array("rn", "r", "n"), ' ', $str));

    if (strlen($str) <= $n)
    {
        return $str;
    }

    $out = "";
    foreach (explode(' ', trim($str)) as $val)
    {
        $out .= $val.' ';

        if (strlen($out) >= $n)
        {
            $out = trim($out);
            return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
        }
    }
 }

You can use the function:

echo character_limiter($text, 200);

If you need to avoid HTML tags, you can use strip_tags function before calling the character_limiter function.

Answer by Starx

There is a simple function called substr($string, $position, $length), which can do this.

Use it like

$brief = substr($bigContent, 0, 200); //for 200 chars

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!