What is the challenge of truncating text intelligently in PHP to fit within a limited space on a webpage?

When truncating text intelligently in PHP to fit within a limited space on a webpage, the challenge is to ensure that the text is cut off at a logical point such as at the end of a sentence or word, without breaking words or cutting off in the middle of a word. One way to solve this is by using functions like `substr` to find the nearest space or punctuation mark before the character limit and truncate the text at that point.

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

// Example usage
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$truncatedText = truncateText($text, 30);
echo $truncatedText; // Output: "Lorem ipsum dolor sit amet..."