Skip to content
PHP Logo

What are common methods for handling text truncation in PHP when displaying content from a MySQL database?

When displaying content from a MySQL database in PHP, it is common to encounter situations where the text needs to be truncated to fit a certain length on the webpage. One common method for handling text truncation is to use PHP's substr() function to extract a portion of the text and append an ellipsis (...) to indicate that the text has been truncated.

php
// Retrieve the content from the database
$content = $row['content'];

// Check if the content exceeds a certain length
if(strlen($content) > 100) {
    // Truncate the content and append an ellipsis
    $truncated_content = substr($content, 0, 100) . '...';
} else {
    $truncated_content = $content;
}

// Display the truncated content
echo $truncated_content;