【问题标题】:Laravel internal linksLaravel 内部链接
【发布时间】:2017-04-03 23:33:46
【问题描述】:

我正在寻找一些将关键字从帖子变成内部链接的代码示例。

在帖子表中,我有正文属性,其中是帖子的文本。我制作了额外的表格“关键字”,其中单词和 URL 属性。

所以我需要脚本,它会自动识别添加到表“关键字”中的单词,并在帖子文本中找到这个单词并将这个单词转换为超链接。请大家帮帮我好吗?

use App\Post;
use App\Category;
use App\Keyword;


public function getSingle($slug) {
    // fetch from the DB based on slug
    $categoriesall = Category::all();
    $post = Post::where('slug', '=', $slug)->first();

    // return the view and pass in the post object
    return view('news.single')->withPost($post)->withCategoriesall($categoriesall);
}

【问题讨论】:

    标签: laravel laravel-5


    【解决方案1】:

    这只是您正在构建的任何东西的起点

    public function getSingle($slug) {
        $keywords = Keyword::get()->toArray();
        $categoriesall = Category::all();
        $post = Post::where('slug', '=', $slug)->first();
    
        $post->text = $this->transform($keywords, $post->text);
        return view('news.single', compact('post', 'categoriesall'));
    }
    
    private function transform($keywords, $text)
    {
         //takes 2 parameters
         //1st parameter is keywords array
         //2nd parameter is text to be transformed
    
         $words = explode(" ", $text); //split wherever we have space 
    
         foreach( $words as $key => $value ) {
             if ( in_array($value, $keywords) ) {
                 $words[$key] = "<a href="/search?keywords=" . $value . ">. $value .</a>";
             }
         }
    
         $paragraph = implode(" ", $words);
         return $paragraph;
    }
    

    请记住,这是一个起点,因为此解决方案根本没有优化。例如:如果您的文本包含 html 标签,这些标签可能会被转换为锚点,因为该算法使用空格作为分隔符;并且大多数时候 html 中都有空格。

    【讨论】:

      猜你喜欢
      • 2018-11-08
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 2021-08-19
      • 2014-01-15
      • 2011-06-05
      相关资源
      最近更新 更多