Tutorial Options to Truncate Strings
Technique #1: Simple
function myTruncate($string, $limit, $break=".", $pad="...") {
if(strlen($string) <= $limit) return $string;
if(false !== ($breakpoint = strpos($string, $break, $limit))) {
if($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . $pad; }
} return $string;
}
Technique #2: Simple
function ellipsis($text, $max=100, $append='…') {
if (strlen($text) <= $max) return $text;
$out = substr($text,0,$max);
if (strpos($text,' ') === FALSE) return $out.$append;
return preg_replace('/\w+$/','',$out).$append;
}
Usage:
<?php
$text = "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.";
echo ellipsis($text,100);
?>
Technique #3: More Options
Options to use PHP's php_tidy to fix up broken HTML, or to strip HTML entirely.
function summarise( $input, $break = " ", $end_text = "...", $limit = 255, $tidy_html = 1, $strip_html = 0 ) {
if ( strlen( $input ) >= $limit ) {
$breakpoint = strpos( $input, $break, $limit );
$input = substr( $input, 0, $breakpoint ) . $end_text;
}
if ( $tidy_html == 1 ) {
ob_start( );
$tidy = new tidy;
$config = array( 'indent' => true, 'output-xhtml' => true, 'wrap' => 200, 'clean' => true, 'show-body-only' => true );
$tidy->parseString( $input, $config, 'utf8' );
$tidy->cleanRepair( );
$input = $tidy;
}
if ( $strip_html == 1 ) {
$input = strip_tags( $input );
}
return $input;
}
Technique #4: Without a function
<?php
$long_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$max_length = 40; // we want to show only 40 characters.
if (strlen($long_text) > $max_length)
{
$short_text = (substr($long_text,0,$max_length-1)); // make it $max_length chars long
$short_text .= "..."; // add an ellipses ... at the end
$short_text .= "<a href='http://example.com/page.html'>Read more</a>"; // add a link
echo $short_text;
}
else
{
// string is already less than $max_length, so display the string as is
echo $long_text;
}
?>