What are the best practices for handling text manipulation in PHP, especially when dealing with character limits?

When handling text manipulation in PHP, especially when dealing with character limits, it's important to ensure that the text is properly truncated without cutting off words or breaking sentences. One common approach is to use the `substr` function to limit the number of characters in a string, while also checking for word boundaries to avoid cutting off in the middle of a word. Additionally, you can use functions like `strlen` and `mb_strlen` to accurately count the number of characters in a multi-byte string.

function truncateText($text, $limit) {
    if (mb_strlen($text) <= $limit) {
        return $text;
    } else {
        $truncated = mb_substr($text, 0, $limit);
        $last_space = mb_strrpos($truncated, ' ');
        return ($last_space === false) ? $truncated : mb_substr($truncated, 0, $last_space);
    }
}

$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$limited_text = truncateText($text, 20);
echo $limited_text;