balazs
11/21/2018 - 11:34 AM

PHP text excerpt - shortening text

Shortening a long text with or without cutting the last word and using a cut off string as '...' or 'Read more...'

<?php

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


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