I have a news page where I pull all the information from the Database. I print the title with a {{ $item->titulo }}
without any problem. The problem comes to me when I put the description, when using textarea
the TinyMCE in the database, it saves it in the following way, <p>La idea de <strong>High As</strong> nació donde ....
so to show it on the page I do like this:
@php echo Str::limit($item->cuerpo, 150) @endphp
In this way it does not remove them <p>
and formats the text well. But the problem comes to me that in those 150 characters if it catches a <b>
in the middle, it destroys the following iterations of the news and puts everything in <b>
.
Any suggestion??
Having the PHP libxml extension installed, it would be easiest to use
loadHTML()
theDOMDocument
. This auto parses malformed HTML and a subsequent call tosaveHTML()
will generate valid HTML.I leave you a snnipet of laravel playground:
https://laravelplayground.com/#/snippets/dfb13f3a-5378-4bc6-82e8-bccd266e3b7e
Ref: Document Object Model
If you can't install the extension
libxml
for some reason, you can call regex. For example:Snnipet from laravel playground:
https://laravelplayground.com/#/snippets/3aee73af-1ad7-4651-a121-7c7ece77c5dd
Finally, to not have all that ugly code in your view, you can create a custom helper
To start you must create a file in a project directory, you can use for example
app
:Then you must modify the file
composer.json
to add a keyfiles
under the key:autoload
:Finally you must execute:
Your helper will be added and you can use it anywhere like