2017-04-03 121 views
0

我正在寻找一些代码示例,使关键字从邮政进入内部链接。Laravel内部链接

在职位表我有身体属性在哪里是文章的文章。而我做额外的表“关键字”在哪里是单词和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); 
} 

回答

0

这只是无论你正在构建

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中都有空格。