What are some best practices for efficiently truncating text in PHP without losing content?
When truncating text in PHP, it's important to consider the content and ensure that the truncation does not cut off words or important information. One common approach is to truncate the text at a specific character limit while preserving whole words. This can be achieved by finding the last space before the character limit and truncating the text at that point.
function truncateText($text, $limit) {
if (strlen($text) > $limit) {
$text = substr($text, 0, strrpos(substr($text, 0, $limit), ' '));
}
return $text;
}
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$truncatedText = truncateText($text, 20);
echo $truncatedText;