php 实现@好友
实现@好友功能
在PHP中实现@好友功能,通常涉及前端交互和后端处理的结合。以下是一个完整的实现方案:
前端部分 在文本输入框中监听用户输入,检测@符号并显示好友列表供选择。可以使用jQuery或原生JavaScript实现:
$('#content').on('input', function() {
let content = $(this).val();
let lastAtPos = content.lastIndexOf('@');
if(lastAtPos !== -1) {
let query = content.substring(lastAtPos + 1);
if(query.length > 0) {
$.ajax({
url: '/get_friends.php',
data: {q: query},
success: function(data) {
showFriendList(data);
}
});
}
}
});
后端处理 创建获取好友列表的接口,根据输入的关键词返回匹配的好友:
// get_friends.php
$q = $_GET['q'] ?? '';
$friends = []; // 从数据库查询好友列表
// 示例数据库查询
$stmt = $pdo->prepare("SELECT id, username FROM users WHERE username LIKE ? LIMIT 10");
$stmt->execute(["%$q%"]);
$friends = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json');
echo json_encode($friends);
存储处理 当用户提交内容时,解析内容中的@好友并存储:
// store_content.php
$content = $_POST['content'];
preg_match_all('/@([^\s]+)/', $content, $matches);
foreach($matches[1] as $username) {
// 获取用户ID并建立关联关系
$stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();
if($user) {
// 存储用户提及关系
$stmt = $pdo->prepare("INSERT INTO mentions (content_id, user_id) VALUES (?, ?)");
$stmt->execute([$contentId, $user['id']]);
}
}
显示处理 在显示内容时,将@用户名转换为可点击的链接:
function parseMentions($content) {
return preg_replace('/@([^\s]+)/', '<a href="/user/$1">@$1</a>', $content);
}
数据库设计
需要创建相关表来存储提及关系:
CREATE TABLE mentions (
id INT AUTO_INCREMENT PRIMARY KEY,
content_id INT NOT NULL,
user_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (content_id) REFERENCES contents(id),
FOREIGN KEY (user_id) REFERENCES users(id)
);
通知功能
当用户被@时,可以添加通知功能:
// 在存储提及关系后
$notification = "你被@提及了";
$stmt = $pdo->prepare("INSERT INTO notifications (user_id, content, is_read) VALUES (?, ?, 0)");
$stmt->execute([$user['id'], $notification]);
性能优化
对于大量用户的情况,可以考虑以下优化:

- 使用Redis缓存好友列表
- 对提及检测使用更高效的正则表达式
- 实现异步处理提及通知
这个实现方案涵盖了从用户输入到存储再到显示的完整流程,可以根据具体需求进行调整和扩展。






