Search code examples
phpstringlaraveleloquenttinymce

How to get plain text from html in laravel model?


I've a database column named description in which i've saved input from tinymce editor. data is something like this,

<p><strong>Paragliding </strong></p>
<p>Paragliding is the recreational and competitive adventure sport of flying paragliders: lightweight, free-flying, foot-launched glider aircraft with no rigid primary structure. The pilot sits in a harness suspended below a fabric wing.<br /> </p>

I can easily display the data in view with following,

{{$data->description}} or {!! $data->description !!}

But, I need some processing to get 30 words from text with following code in model,

/**
 * @param $sentence
 * @param int $count
 * @return mixed
 */
function get_words($sentence, $count = 30) {
    preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
    return $matches[0];
}

/**
 * @return short_description
 */
public function shortDescription()
{
    return $this->get_words($this->description);
}

and I'm currently geting empty when I call shortDescription function.

Is there any way to get plain text from $this->description variable ?

Any suggestion help is appreciated.


Solution

  • You can use strip_tags() php function for get only text,

    $text = "<p><strong>Paragliding </strong></p>
    <p>Paragliding is the recreational and competitive adventure sport of flying paragliders: lightweight, free-flying, foot-launched glider aircraft with no rigid primary structure. The pilot sits in a harness suspended below a fabric wing.<br /> </p>";
    $plainText = strip_tags($text);
    

    output,

    "Paragliding Paragliding is the recreational and competitive adventure sport of flying paragliders: lightweight, free-flying, foot-launched glider aircraft with no rigid primary structure. The pilot sits in a harness suspended below a fabric wing. "

    further details you can see, http://php.net/manual/en/function.strip-tags.php

    /**
     * @return short_description
     */
    public function getShortDescriptionAttribute()
    {
        $taglessDescription = strip_tags($this->description);
        return Str::words($taglessDescription, 30, '....');
    }
    

    Blade File

    {{ $data->short_description }}