What is the best way to limit the character count of a string in PHP without cutting off words?

When limiting the character count of a string in PHP, it's important to ensure that words are not cut off in the middle. One way to achieve this is by using the `substr` function along with `strpos` to find the nearest space before the character limit and then truncate the string at that point.

function limitString($string, $limit) {
    if (strlen($string) <= $limit) {
        return $string;
    }
    
    $trimmed = substr($string, 0, $limit);
    $lastSpace = strrpos($trimmed, ' ');
    
    if ($lastSpace !== false) {
        $trimmed = substr($trimmed, 0, $lastSpace);
    }
    
    return $trimmed;
}

// Example usage
$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$limitedString = limitString($string, 20);
echo $limitedString; // Output: "Lorem ipsum dolor"