What are some potential pitfalls when trying to shorten a text in PHP while maintaining whole words?
When trying to shorten a text in PHP while maintaining whole words, a potential pitfall is cutting off words in the middle, which can lead to readability issues. To solve this, you can use the `substr` function to find the nearest space before the desired character limit and truncate the text at that point.
function shortenText($text, $limit) {
if (strlen($text) <= $limit) {
return $text;
}
$shortenedText = substr($text, 0, $limit);
$lastSpace = strrpos($shortenedText, ' ');
if ($lastSpace !== false) {
$shortenedText = substr($shortenedText, 0, $lastSpace);
}
return $shortenedText;
}
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$shortenedText = shortenText($text, 20);
echo $shortenedText;