What alternative methods can be used to effectively limit the number of words or characters in a string without causing issues like "Undefined array key" warnings?

When limiting the number of words or characters in a string in PHP, it is important to check if the string is not empty before attempting to access array keys. Using functions like `explode()` or `str_split()` can help split the string into an array of words or characters before limiting them. Additionally, using `isset()` or `array_key_exists()` can prevent "Undefined array key" warnings when accessing specific elements of the array.

$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$words = explode(' ', $string);
$limited_words = array_slice($words, 0, 5); // Limiting to 5 words

$limited_string = implode(' ', $limited_words);
echo $limited_string;