Skip to content

Instantly share code, notes, and snippets.

@bklein01
Forked from stankusl/excerpt.md
Created July 23, 2019 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bklein01/fc809efd2daa8ebf11950ea76137eff3 to your computer and use it in GitHub Desktop.
Save bklein01/fc809efd2daa8ebf11950ea76137eff3 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment