Truncating Text on Word Boundaries : strrev « String « PHP






Truncating Text on Word Boundaries

 
<?php
function truncate_text_nicely($string, $max, $moretext) {
    if (strlen($string) > $max) {
        $max -= strlen($moretext);

        $string = strrev(strstr(strrev(substr($string, 0, $max)), ' '));

        $string .= $moretext;
    }

    return $string;
}

$str = 'This is a test.This is a test.This is a test.This is a test.This is a test.This is a test.';

$values = truncate_text_nicely($str, 20, '...');

echo "<pre>{$values}</pre>";
?>
  
  








Related examples in the same category

1.Reversing Strings: string strrev ( string string )
2.Reversing a string by byte
3.Reversing Strings