What is the common issue faced when truncating text in PHP scripts?

When truncating text in PHP scripts, a common issue is that the truncation might cut off the text in the middle of a word, leading to an incomplete or awkward display. To solve this issue, you can use functions like `substr` to truncate the text at a specific length while ensuring that it ends at the end of a word.

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

// Example usage
$text = "This is a sample text that needs to be truncated.";
$truncated_text = truncate_text($text, 20);
echo $truncated_text;