Skip to content
PHP Logo

What are the drawbacks of using wordwrap() function in PHP for text truncation?

The main drawback of using the wordwrap() function in PHP for text truncation is that it may not accurately truncate the text at the desired length, especially if the text contains HTML tags or special characters. To solve this issue, you can use the substr() function to truncate the text without breaking HTML tags or special characters.

php
function truncate_text($text, $length) {
    if (strlen($text) > $length) {
        $text = substr($text, 0, $length);
        $text = substr($text, 0, strrpos($text, ' '));
        $text .= '...';
    }
    return $text;
}

$text = "<p>This is a sample text with <strong>HTML</strong> tags that needs to be truncated.</p>";
$truncated_text = truncate_text($text, 50);
echo $truncated_text;