What are some potential pitfalls to consider when limiting text length in PHP?
When limiting text length in PHP, one potential pitfall to consider is the possibility of cutting off words in the middle when truncating the text. To avoid this issue, you can use the `substr` function to limit the text length while ensuring that the text is not cut off in the middle of a word.
function limit_text($text, $limit) {
if (strlen($text) > $limit) {
$text = substr($text, 0, $limit);
$text = substr($text, 0, strrpos($text, ' '));
$text .= '...';
}
return $text;
}
// Example usage
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$limited_text = limit_text($text, 20);
echo $limited_text; // Output: "Lorem ipsum dolor..."