php实现微博@
实现微博@功能的方法
在PHP中实现微博的@功能,可以通过正则表达式匹配、数据库查询和前端交互完成。以下是具体实现步骤:
匹配用户昵称
使用正则表达式匹配文本中的@符号和用户昵称:
$pattern = '/@([a-zA-Z0-9_\x{4e00}-\x{9fa5}]+)/u';
preg_match_all($pattern, $content, $matches);
$mentionedUsers = array_unique($matches[1]);
查询用户ID
根据匹配到的昵称查询数据库获取用户ID:

foreach ($mentionedUsers as $username) {
$user = $db->query("SELECT id FROM users WHERE username = '$username'");
if ($user) {
$mentionedUserIds[] = $user['id'];
}
}
存储提及关系
将提及信息存入数据库:
foreach ($mentionedUserIds as $userId) {
$db->insert('mentions', [
'post_id' => $postId,
'user_id' => $userId,
'created_at' => date('Y-m-d H:i:s')
]);
}
前端高亮显示
使用JavaScript实现前端@用户的高亮效果:

function highlightMentions(text) {
return text.replace(/@([a-zA-Z0-9_\u4e00-\u9fa5]+)/g, '<span class="mention">@$1</span>');
}
发送通知
当用户被@时发送通知:
foreach ($mentionedUserIds as $userId) {
$notification = [
'user_id' => $userId,
'type' => 'mention',
'data' => json_encode(['post_id' => $postId]),
'created_at' => date('Y-m-d H:i:s')
];
$db->insert('notifications', $notification);
}
安全性考虑
对用户输入进行过滤防止XSS攻击:
$content = htmlspecialchars($content, ENT_QUOTES, 'UTF-8');
以上方法组合使用可以实现完整的微博@功能,包括识别提及、存储关系、前端展示和通知提醒。






