如何在foreach循环中查询preg_match_all结果?

How to query preg_match_all results in foreach loop?

所以我正在开发一个像 Twitter 这样的用户标记系统,用户可以在评论中互相标记,如下所示:"blablabla @username blablabla"。我正在使用 preg_replace 查找文本中的“@username”并将其转换为可点击的 link,并在插入数据库时​​使用 preg_match_all。

$text = preg_replace('/(^|\s)@(\w+)/', '<a href="profile.php?poet_id=" class="small">@</a>', $text);

    $sanitized_comment = trim(mysql_real_escape_string(htmlspecialchars($_POST['comment'])));

if (preg_match_all("/(^|\s)@(\w+)/", $sanitized_comment, $matches)) {
        $mentions = array_unique($matches[0]);

        foreach($mentions as $mention) {
            mysql_query("INSERT INTO `comments_mentions` SET `cm_comment_id` = @last_comment_id, `cm_mentioned` = '" . $mention . "', `cm_mentioner` = " . (int)$session_user_id . "");
        }
    }

这很好用。

我现在要做的是查找并存储已在文本中标记的用户的 "user_id",而不是他们的 "username"。

我试过

    $sanitized_comment = trim(mysql_real_escape_string(htmlspecialchars($_POST['comment'])));

if (preg_match_all("/(^|\s)@(\w+)/", $sanitized_comment, $matches)) {
    $mentions = array_unique($matches[0]);

    foreach($mentions as $mention) {
        $user_id_from_username = mysql_fetch_assoc(mysql_query("SELECT `user_id` FROM `users` WHERE lower(`username`) = lower(substr('" . $mention . "', 2))"));
        mysql_query("INSERT INTO `comments_mentions` SET `cm_comment_id` = @last_comment_id, `cm_mentioned` = " . $user_id_from_username . ", `cm_mentioner` = " . (int)$session_user_id . "");
    }
}

但这只会将一行(第一个值)插入到数据库中,即使标记了多个人也是如此。

如何正确查询每个提到的用户 "username" 的 "user_id",然后将这些 ID 存储在我的数据库中的行中(如果标记了多个人,则为多个)?

$mentions = array_unique($matches[0]); 之前尝试 var_dump($matches)。我不确定,但我希望用户名存储在 $matches[2].

您也可以给 (\w+) 起个名字,这样事情就容易多了。该模式应类似于:

/(^|\s)@(?P<username>\w+)/

在执行 preg_match_all 时,您可以获得这样的用户名:

$mentions = array_unique($matches['username']);

还有在评论中说的。使用 mysql 是不好的。使用 PDO 或 mysqli。