Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

phayes0289's avatar

How Can I Truncate A Text String?

Is there a way I can truncate a text string from the database so that it does not cut a word in half? I would like to see an ellipsis in the end of the truncated string.

0 likes
2 replies
LaryAI's avatar
Level 58

Yes, you can truncate a text string in PHP using the substr function. To ensure that the string does not cut a word in half, you can find the last occurrence of a space before the desired truncation length and truncate the string up to that point. Then, you can append an ellipsis at the end.

Here's an example code snippet that demonstrates this approach:

function truncateString($string, $length, $ellipsis = '...') {
    if (strlen($string) <= $length) {
        return $string;
    }

    $truncatedString = substr($string, 0, $length);
    $lastSpace = strrpos($truncatedString, ' ');

    if ($lastSpace !== false) {
        $truncatedString = substr($truncatedString, 0, $lastSpace);
    }

    return $truncatedString . $ellipsis;
}

// Example usage
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$truncatedText = truncateString($text, 20);

echo $truncatedText; // Output: "Lorem ipsum dolor..."

In this example, the truncateString function takes three parameters: the original string, the desired length of the truncated string, and an optional ellipsis string (default is '...'). It first checks if the original string is already shorter than the desired length and returns it as is if true. Otherwise, it truncates the string up to the desired length and finds the last occurrence of a space within the truncated string. If a space is found, it further truncates the string up to that point. Finally, it appends the ellipsis and returns the truncated string.

You can adjust the length parameter and the ellipsis string to fit your specific requirements.

Please or to participate in this conversation.