preg_match_all 在所有输入字段中

preg_match_all in all input fields

我使用 preg_match_all 在 'body' 中查找用户名并将它们保存在数据库中。如何在多个输入字段中找到用户名,例如:body、title 和 article?以及如何在不保存重复条目的情况下将找到的引用保存到数据库中?

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

            }
        }

您可以使用 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();
         }
     }
}

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


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

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