代码之家  ›  专栏  ›  技术社区  ›  Sagar Gautam

如何在laravel模型中从html中获取纯文本?

  •  1
  • Sagar Gautam  · 技术社区  · 6 年前

    我有一个数据库列,名为 description

    <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>
    

    我可以通过以下方式轻松显示视图中的数据:,

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

    但是,我需要一些处理来从文本中获得30个单词,模型中的代码如下,

    /**
     * @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);
    }
    

    我现在打电话的时候已经空了 shortDescription 作用

    $this->description 变量

    如有任何建议或帮助,我们将不胜感激。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Md.Sukel Ali    6 年前

    $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);
    

    输出

    “滑翔伞是一种娱乐性和竞争性的冒险活动 飞行滑翔伞运动:轻巧、自由飞行、脚部发射 无刚性主结构的滑翔机。飞行员坐在一个座位上

    你可以看到更多的细节, http://php.net/manual/en/function.strip-tags.php

        2
  •  0
  •   John Conde    4 年前
    {{strip_tags(Illuminate\Support\Str::words($item->description,30))}}
    //this will print 30 words
    
    {!! html_entity_decode($data->description) !!}
    //this will print with html
    

    {strip_tags($data->description)}
     //this will strip your HTML tags
    
    { Illuminate\Support\Str::limit($data->description,30)}} // this will print 30 character with 3 dots default
    

    在版本5.8+中,删除了str帮助程序,您必须使用 Illuminate\Support\Str::limit($string) str_limit install composer require laravel/helpers 用这个

    {{substr(strip_tags($item->description),0,5)}} //this will print 30 character
    
    {{strip_tags(Illuminate\Support\Str::limit($item->description,30))}} //this will print 30 character
    
    {{strip_tags(Illuminate\Support\Str::words($item->description,30))}} //this will print 30 words
    

    laravel