truncate function in PHP

Posted on: July 12th, 2022
By: Tadeo Martinez

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. Required fields are marked *