How can PHP be used to truncate text to a specific length without cutting off in the middle of a word?

When truncating text to a specific length in PHP, it is important to ensure that the text does not get cut off in the middle of a word. One way to solve this issue is to find the last space before the desired truncation length and truncate the text at that point. This way, the text will be cut off at the end of a word.

function truncateText($text, $length) {
    if (strlen($text) > $length) {
        $text = substr($text, 0, strrpos($text, ' ', $length - strlen($text))) . '...';
    }
    return $text;
}

$text = "This is a sample text that needs to be truncated to a specific length without cutting off in the middle of a word.";
$truncatedText = truncateText($text, 50);
echo $truncatedText;