What are some potential issues with cutting off a string in PHP after a certain number of characters, particularly when a word is cut off in the middle?

When cutting off a string in PHP after a certain number of characters, one potential issue is that a word may be cut off in the middle, resulting in an incomplete or incorrect output. To solve this issue, you can use the `substr` function to find the last space before the character limit and cut the string there to ensure that words are not split.

function truncateString($string, $limit) {
    if (strlen($string) > $limit) {
        $string = substr($string, 0, strrpos(substr($string, 0, $limit), ' '));
    }
    return $string;
}

// Example usage
$string = "This is a long string that needs to be truncated";
$truncatedString = truncateString($string, 20);
echo $truncatedString;