What are some common methods in PHP to truncate text for display on a website, similar to the "Read More" feature in WordPress?
One common method in PHP to truncate text for display on a website is to use the `substr` function to limit the number of characters shown. Another method is to use the `wordwrap` function to break the text into smaller chunks. You can also use regular expressions to find a specific point in the text to truncate.
function truncate_text($text, $limit) {
if (strlen($text) > $limit) {
$text = substr($text, 0, $limit);
$text = substr($text, 0, strrpos($text, ' '));
$text .= '...';
}
return $text;
}
// Example usage
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
$truncated_text = truncate_text($text, 30);
echo $truncated_text;