How to find #hashtags in strings using Laravel 4.1

2020-05-01 07:05发布

问题:

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.