How can PHP be used to truncate text to a specific length without cutting off in the middle of a word?
When truncating text to a specific length in PHP, it is important to ensure that the text does not get cut off in the middle of a word. One way to solve this issue is to find the last space before the desired truncation length and truncate the text at that point. This way, the text will be cut off at the end of a word.
function truncateText($text, $length) {
if (strlen($text) > $length) {
$text = substr($text, 0, strrpos($text, ' ', $length - strlen($text))) . '...';
}
return $text;
}
$text = "This is a sample text that needs to be truncated to a specific length without cutting off in the middle of a word.";
$truncatedText = truncateText($text, 50);
echo $truncatedText;
Keywords
Related Questions
- How can one efficiently iterate through query results in PHP to populate an array with specific data?
- How can conditional statements be effectively implemented in PHP templates without using eval(), based on the discussions in the forum thread?
- How can URL encoding impact the display of special characters like "#" in PHP?