preg_match_all 提及用户@ Laravel
preg_match_all mention user @ Laravel
我想在 post 中找到提到的用户并将其保存在 table 中。这里是所有输入的用户名,写在@符号后面的post和table"User"中找到并由用户存储ID。不幸的是,我找不到任何用户,因此找不到用户 ID。我如何从用户那里找到ID?
$msg = I am a post and mention @username1 and @username2
preg_match_all('/@(\w+)/', $msg, $mentionedUsers);
foreach ($mentionedUsers[0] as $mentionedUser) {
$foundUser = User::find($mentionedUser);
if ($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[0]
是一个完整匹配的数组,以 @
开头的字符串,然后有 1+ 个单词字符。用户名是没有 @
的部分,被捕获到第 1 组。
因此,您需要使用
foreach ($mentionedUsers[1] as $mentionedUser)
^
然后,您将拥有前面没有 @
的用户 ID。
此外,如果您想避免匹配电子邮件,您可以在正则表达式中的 @
之前添加 \B
:
'/\B@(\w+)/'
然后,@
字符只有在其前面没有字符字符时才会被匹配。
我想在 post 中找到提到的用户并将其保存在 table 中。这里是所有输入的用户名,写在@符号后面的post和table"User"中找到并由用户存储ID。不幸的是,我找不到任何用户,因此找不到用户 ID。我如何从用户那里找到ID?
$msg = I am a post and mention @username1 and @username2
preg_match_all('/@(\w+)/', $msg, $mentionedUsers);
foreach ($mentionedUsers[0] as $mentionedUser) {
$foundUser = User::find($mentionedUser);
if ($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[0]
是一个完整匹配的数组,以 @
开头的字符串,然后有 1+ 个单词字符。用户名是没有 @
的部分,被捕获到第 1 组。
因此,您需要使用
foreach ($mentionedUsers[1] as $mentionedUser)
^
然后,您将拥有前面没有 @
的用户 ID。
此外,如果您想避免匹配电子邮件,您可以在正则表达式中的 @
之前添加 \B
:
'/\B@(\w+)/'
然后,@
字符只有在其前面没有字符字符时才会被匹配。