truncate function in PHP - Brown Surfing

truncate function in PHP

Posted on: July 12th, 2022
By: Efrain Lemus

I found this code from this StackOverflow question.

function truncate($text, $chars = 25) {
    if (strlen($text) <= $chars) {
        return $text;
    }
    $text = $text." ";
    $text = substr($text,0,$chars);
    $text = substr($text,0,strrpos($text,' '));
    $text = $text."...";
    return $text;
}

$description = get_sub_field('full_description');
echo truncate($description, 75);

Have any questions or comments? Write them below!


Leave a Reply

Your email address will not be published.