Skip to content
PHP Logo

When truncating text in PHP, what are some best practices for ensuring that the truncated text remains readable and coherent, especially in cases where the truncation point falls within a word?

When truncating text in PHP, it's important to ensure that the truncated text remains readable and coherent, especially when the truncation point falls within a word. One common approach is to find the nearest space or punctuation mark before the truncation point to avoid cutting off words mid-way. This can be achieved by using functions like `strrpos` to find the last occurrence of a space or punctuation mark before the truncation point.

php
function truncateText($text, $maxLength) {
    if (strlen($text) <= $maxLength) {
        return $text;
    }

    $lastSpace = strrpos(substr($text, 0, $maxLength), ' ');

    if ($lastSpace !== false) {
        return substr($text, 0, $lastSpace) . '...';
    }

    return substr($text, 0, $maxLength) . '...';
}

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