How can PHP be used to automatically truncate long words in a fixed layout, such as a guestbook?

When displaying user-submitted content in a fixed layout like a guestbook, long words can disrupt the design. To automatically truncate long words, you can use PHP to check the length of each word and trim it if it exceeds a certain limit. This ensures that the layout remains tidy and user-friendly.

function truncateLongWords($text, $maxLength) {
    $words = explode(' ', $text);
    foreach ($words as $key => $word) {
        if (strlen($word) > $maxLength) {
            $words[$key] = substr($word, 0, $maxLength) . '...';
        }
    }
    return implode(' ', $words);
}

// Example usage
$longText = "This is a verylongwordthatneedstobetruncated in a guestbook layout.";
$truncatedText = truncateLongWords($longText, 10);
echo $truncatedText;