PHP Truncating Text On Word Boundaries – String Function

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

“;
?>

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.