How to find #hashtags in strings using Laravel 4.1?

江枫思渺然 提交于 2020-01-11 12:55:10

问题


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.

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();

I found some functions in this cheat sheet (http://cheats.jesse-obrien.ca) but I do not get them to work properly.


回答1:


Try this:

$str = $hashtag_string;

       preg_match_all('/#(\w+)/', $str, $matches);


       foreach ($matches[1] as $hashtag_name) {

       $hashtag =   Hashtag::firstOrCreate(array('hashtag' => $hashtag_name));

                                    }

You could then, in this foreach loop, connect those hashtags to a post (or in your case a photo) or sth.



来源:https://stackoverflow.com/questions/21200492/how-to-find-hashtags-in-strings-using-laravel-4-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!