What are the limitations of wordwrap() in terms of breaking text based on character count versus pixel width?

The limitation of wordwrap() when breaking text based on character count is that it does not take into account the actual width of the characters being displayed. This can result in uneven line breaks when displaying text in a fixed-width container. To address this issue, we can use the imagettfbbox() function to calculate the pixel width of the text and then break it accordingly.

function customWordwrap($text, $width) {
    $lines = [];
    $line = '';
    $words = explode(' ', $text);
    
    foreach ($words as $word) {
        $testLine = $line . ' ' . $word;
        $bbox = imagettfbbox(12, 0, 'arial.ttf', $testLine);
        
        if ($bbox[2] > $width) {
            $lines[] = $line;
            $line = $word;
        } else {
            $line = $testLine;
        }
    }
    
    $lines[] = $line;
    
    return implode("\n", $lines);
}

$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
$wrappedText = customWordwrap($text, 200);
echo $wrappedText;