如何使用Laravel 4.1在字符串中查找#hashtags? [英] How to find #hashtags in strings using Laravel 4.1?
问题描述
我目前正在尝试通过Input字符串进行过滤,以查找用户希望与他的照片一起显示的单个主题标签.但是,我当前在数据库中得到的插入不正确.
I am currently trying to filter through an Input string to find the single hashtags that a user wants to be displayed with his photo. However, I am currently getting inserts in my database that are not correct.
最好的情况是将每个标签标签保存在带有照片ID的新数据库行中.但是,我真的不知道该怎么做.
The best case scenario would be that every single hashtag is saved in a new database row with the photo id. However, I do not really know what to do to accomplish that.
$hashtag = new Hashtag;
$hashtag->photo_id = $photo->id;
$hashtag_string = Input::get('hashtags');
$hashtag_string = Str::contains($hashtag_string, '#')
$hashtag->hashtag = $hashtag_string;
$hashtag->save();
我在该备忘单中找到了一些功能( http://cheats.jesse-obrien.ca ),但我无法使它们正常工作.
I found some functions in this cheat sheet (http://cheats.jesse-obrien.ca) but I do not get them to work properly.
推荐答案
尝试一下:
$str = $hashtag_string;
preg_match_all('/#(\w+)/', $str, $matches);
foreach ($matches[1] as $hashtag_name) {
$hashtag = Hashtag::firstOrCreate(array('hashtag' => $hashtag_name));
}
然后,您可以在此foreach循环中,将这些标签与帖子(或您的照片)或某物相连.
You could then, in this foreach loop, connect those hashtags to a post (or in your case a photo) or sth.
这篇关于如何使用Laravel 4.1在字符串中查找#hashtags?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!