Skip to content
PHP Logo

How can you prevent words from being cut off when truncating a string in PHP?

When truncating a string in PHP, one common issue is that words may be cut off in the middle if the truncation point falls in the middle of a word. To prevent this, you can find the last space before the truncation point and truncate the string at that position instead. This ensures that words are not cut off and the string is truncated cleanly.

php
function truncateString($string, $maxLength) {
    if(strlen($string) > $maxLength) {
        $string = substr($string, 0, $maxLength);
        $lastSpace = strrpos($string, ' ');
        $string = substr($string, 0, $lastSpace);
        $string .= '...';
    }
    return $string;
}

// Example usage
$string = "This is a long string that needs to be truncated properly";
$truncatedString = truncateString($string, 20);
echo $truncatedString; // Output: "This is a long..."