所有输入字段中的preg_match_all

时间:2019-05-11 20:30:06

标签: php laravel preg-match-all

我使用preg_match_all在“正文”中找到用户名并将其保存在数据库中。如何在几个输入字段中找到用户名,例如:正文,标题和文章?以及如何在不保存重复条目的情况下将找到的引用保存到数据库?

if ($post) {
            preg_match_all('/\B@(\w+)/', $request->get('body'), $mentionedUsers);

            foreach ($mentionedUsers[1] as $mentionedUser) {

            $foundUser = User::where('username', $mentionedUser)->first();
                if(!$foundUser){
                    continue;
                }
            $foundUserId = $foundUser->id;
            $mentionedUser_save = new Mentioned_post_user;
            $mentionedUser_save->user_id_lead = Auth::user()->id;
            $mentionedUser_save->user_id = $foundUserId;
            $mentionedUser_save->post_id = $post->id;
            $mentionedUser_save->save();

            }
        }

1 个答案:

答案 0 :(得分:1)

您可以使用whereIn('user_name', $mentionedUsers)代替运行foreach。

if ($post) {
    // assuming this line works and mentioned users are in $mentionedUsers[1]
    preg_match_all('/\B@(\w+)/', $request->get('body'), $mentionedUsers);

    $foundUsers = User::whereIn('username', $mentionedUsers[1])->get();

    if ($foundUsers) {
        foreach ($foundUsers as $foundUser) {
            $foundUserId = $foundUser->id;
            $mentionedUser_save = new Mentioned_post_user;
            $mentionedUser_save->user_id_lead = Auth::user()->id;
            $mentionedUser_save->user_id = $foundUserId;
            $mentionedUser_save->post_id = $post->id;
            $mentionedUser_save->save();
         }
     }
}

否则,您需要使用$mentionedUsers[1]获得array_unique()的唯一值。 (我建议上面的解决方案)


编辑:对不起,您的问题有所不同。对于您的解决方案,我将使用的方法是合并所有输入。

$theString = "$request->body $request->title $request->article";

preg_match_all('/\B@(\w+)/', $theString, $mentionedUsers);    

$userNamesArray = array_unique($mentionedUsers[1]);

$foundUsers = User::whereIn('username', $userNamesArray)->get();