php实现@用户
PHP 实现用户提及功能(@用户)
在 PHP 中实现类似社交媒体的用户提及功能(@用户),主要涉及字符串处理、数据库查询和前端交互。以下是关键实现步骤:
字符串匹配与提取
使用正则表达式匹配文本中的 @username 格式:
$text = "Hello @user1, check this out!";
preg_match_all('/@([a-zA-Z0-9_]+)/', $text, $matches);
$mentionedUsernames = $matches[1]; // 获取所有被提及的用户名
数据库验证用户
查询数据库验证用户名是否存在,并获取用户ID:
// 假设使用 PDO 连接数据库
$stmt = $pdo->prepare("SELECT user_id FROM users WHERE username = ?");
$mentionedUserIds = [];
foreach ($mentionedUsernames as $username) {
$stmt->execute([$username]);
if ($row = $stmt->fetch()) {
$mentionedUserIds[] = $row['user_id'];
}
}
存储提及关系
在保存内容时(如帖子或评论),记录提及关系:
// 保存主内容(如帖子)
$postId = savePost($userId, $text);
// 保存提及记录
foreach ($mentionedUserIds as $mentionedUserId) {
$stmt = $pdo->prepare("INSERT INTO mentions (post_id, user_id, mentioned_user_id) VALUES (?, ?, ?)");
$stmt->execute([$postId, $userId, $mentionedUserId]);
}
前端高亮显示
使用 JavaScript 或 CSS 高亮显示提及的用户名:
// 前端处理(如使用 jQuery)
$('.post-content').html(function(_, html) {
return html.replace(/@(\w+)/g, '<span class="mention">@$1</span>');
});
CSS 样式:
.mention {
color: #1da1f2;
font-weight: bold;
}
用户通知
通过邮件或站内信通知被提及的用户:
foreach ($mentionedUserIds as $mentionedUserId) {
$notification = "You were mentioned by @$username in a post.";
sendNotification($mentionedUserId, $notification);
}
自动补全(可选)
实现前端输入时的用户名自动补全:
$('#post-input').on('input', function(e) {
if (e.target.value.includes('@')) {
// 发送 AJAX 请求获取匹配的用户列表
$.get('/api/user/search?q=' + query, function(users) {
// 显示下拉补全列表
});
}
});
安全注意事项
- 对用户输入进行过滤,防止 XSS 攻击。
- 使用预处理语句防止 SQL 注入。
- 限制高频提及操作防止滥用。
通过以上步骤,可以实现完整的用户提及功能,包括后端处理、数据库存储和前端交互。







