2017-04-03 108 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中都有空格。