【发布时间】:2018-02-05 19:47:01
【问题描述】:
如果用户写了一篇文章,他可以在文本中使用主题标签。 文本在 post 表中保存为正文。主题标签是一个以# 开头的词。主题标签存储在标签表中,并且与帖子具有多对多关系。
if($post)
{
preg_match_all('/#(\w+)/', $request->get('body'),$tagNames);
// $tagnames contains an array of results. $tagnames[0] is all matches
$tagIds = [];
foreach($tagNames[0] as $tagName)
{
//$post->tags()->create(['name'=>$tagName]);
//Or to take care of avoiding duplication of Tag
//you could substitute the above line as
$tag = Tag::firstOrCreate(['name'=>$tagName]);
if($tag)
{
$tagIds[] = $tag->id;
}
}
$post->tags()->sync($tagIds);
}
所以我把数据交给视图:
$postall = $user->posts()->with('comments', 'tags')->where('status', 1)->latest()->get();
每个主题标签都有自己的视图,可以在 /tags/id 下访问。现在我想用指向相应视图的 href 元素替换文本中的主题标签。我已经读过 preg_replace 是可能的,但我必须如何以及在哪里使用它?
【问题讨论】:
标签: php laravel function tags preg-replace