2017-04-04 94 views
0

我想與Laravel內部鏈接巫婆將與數據庫中的關鍵字recolonize。Laravel內部鏈接與preg_replace

public function getSingle($slug) { 

    $post = Post::where('slug', '=', $slug)->first(); 

    $keyword = Keyword::all(); 
    $data = array(); 

    foreach($keyword as $word){ 
      $data = $word->keyword; 
      $sentence = preg_replace('@(?<=\W|^)('.$data.')(?=\W|$)@i', '<a href="'.$word->url.'">$1</a>', $post->body); 
    } 


    return view('news.single')->withPost($post)->withSentence($sentence); 
} 

此代碼工作正常,但我有問題的每個循環,因爲它只顯示數據庫中的關鍵字的一個決議。 我嘗試添加數組變量,但它是一樣的。所以我需要修復女巫顯示多個關鍵字不只一個。

回答

0

這是因爲,在每個循環中,您正在將句子重置爲最後一個。試試這個,而不是

public function getSingle($slug) { 

    $post = Post::where('slug', '=', $slug)->first(); 

    $keyword = Keyword::all(); 
    $data = array(); 
    $sentence = $post->body; 

    foreach($keyword as $word){ 
      $data = $word->keyword; 
      $sentence = preg_replace('@(?<=\W|^)('.$data.')(?=\W|$)@i', '<a href="'.$word->url.'">$1</a>', $sentence); 
    } 


    return view('news.single')->withPost($post)->withSentence($sentence); 
} 

因此,你將替換每個關鍵字相同的句子,並返回它的更改版本。