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

Sag*_*tam 2 php string tinymce laravel eloquent

我有一个名为 的数据库列,description我在其中保存了来自tinymce 编辑器的输入。数据是这样的,

<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>
Run Code Online (Sandbox Code Playgroud)

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

{{$data->description}} or {!! $data->description !!}
Run Code Online (Sandbox Code Playgroud)

但是,我需要进行一些处理才能从文本中获取 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);
}
Run Code Online (Sandbox Code Playgroud)

当我调用函数时,我现在变得空了shortDescription

有没有办法从变量中获取纯文本$this->description

任何建议帮助表示赞赏。

Md.*_*Ali 7

您可以使用 strip_tags() php 函数仅获取文本,

$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);
Run Code Online (Sandbox Code Playgroud)

输出,

“滑翔伞 滑翔伞是飞行滑翔伞的娱乐性和竞技性冒险运动:轻型、自由飞行、脚发射的滑翔机,没有刚性的主结构。飞行员坐在悬挂在织物机翼下方的安全带中。”

您可以查看更多详细信息,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, '....');
}
Run Code Online (Sandbox Code Playgroud)

刀片文件

{{ $data->short_description }}
Run Code Online (Sandbox Code Playgroud)