How can PHP be used to truncate news articles to a specific character limit and provide a "Read More" link?
To truncate news articles to a specific character limit in PHP and provide a "Read More" link, you can use the `substr` function to limit the number of characters displayed. You can then check if the truncated text ends in the middle of a word and adjust the substring accordingly. Finally, you can add a "Read More" link that directs users to the full article.
function truncate_text($text, $limit, $suffix = '...') {
if (strlen($text) > $limit) {
$text = substr($text, 0, $limit);
$text = substr($text, 0, strrpos($text, ' ')) . $suffix;
}
return $text;
}
$article = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
$truncated_article = truncate_text($article, 50);
echo $truncated_article;
echo "<a href='full_article.php'>Read More</a>";