'Truncate string with html tag in Laravel
I want to truncate in Laravel text from database with HTML Tag, for example:
<p>Hi. I want to say about my story. </p>
I found a method:
{{ Str::limit($text, 20) }}
But I've problem, because when I truncate this text with length 20, I will have this result:
<p>Hi. I want to say
I want to get text with closed tags in HTML. I know that such a method is available in different framework as soon as CakePHP. What about Laravel?
Solution 1:[1]
It's always preferable to parse HTML properly, but if your text is always contained in a single element, it should be safe to treat it as a simple string:
$html = "<div class='container'><p><span class='cj4'>Here’s the long text to be truncated</span></p></div>";
$text = strip_tags($html);
$short_text = Str::limit($text, 20);
$html = str_replace($text, $short_text, $html);
This results in:
<div class='container'><p><span class='cj4'>Here’s the long text...</span></p></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | miken32 |