Skip to content

Instantly share code, notes, and snippets.

@stankusl
Created May 27, 2015 15:07
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save stankusl/579e436892ef1cdb5d4a to your computer and use it in GitHub Desktop.
Save stankusl/579e436892ef1cdb5d4a to your computer and use it in GitHub Desktop.
Text Excerpt PHP function

Function:

function shorten_text($text, $max_length = 140, $cut_off = '...', $keep_word = false)
{
    if(strlen($text) <= $max_length) {
        return $text;
    }

    if(strlen($text) > $max_length) {
        if($keep_word) {
            $text = substr($text, 0, $max_length + 1);

            if($last_space = strrpos($text, ' ')) {
                $text = substr($text, 0, $last_space);
                $text = rtrim($text);
                $text .=  $cut_off;
            }
        } else {
            $text = substr($text, 0, $max_length);
            $text = rtrim($text);
            $text .=  $cut_off;
        }
    }

    return $text;
}

Usage:

$text = 'These are some words that should be kept completely untouched by the script if $keep_word is set to true';

echo shorten_text($text, 100, ' <a href="?article=129">Read more</a>', true);
@agiannis
Copy link

thanks, maybe change to mb_substr for utf-8 support.

@Nolibois
Copy link

Thanks, it's a good function. It helped me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment