agiannis
9/16/2019 - 4:26 AM

Text Excerpt PHP function

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);