Laravel 内部链接 preg_replace

Laravel internal links with preg_replace

我正在尝试使用 Laravel 内部链接 将使用数据库中的关键字重新定位。

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.'"></a>', $post->body);
    }


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

这段代码工作正常,但我对每个循环都有问题,因为它只显示数据库中的一个关键词。 我尝试添加数组变量,但它是一样的。所以我需要修复 显示多个关键字而不是一个。

这是因为,在每个循环中,您都将句子重置为最后一个。试试这个

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.'"></a>', $sentence);
    }


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

因此,您将为每个关键字替换相同的句子,并且 return 更改了它的版本。