php 实现 at用户
实现 @用户 功能
在 PHP 中实现 @用户 功能,可以通过正则表达式匹配文本中的 @ 符号及用户名,并将其转换为可点击的链接或进行其他处理。以下是一个完整的实现方法:
匹配 @用户 的正则表达式
使用正则表达式匹配以 @ 开头,后跟用户名(可能包含字母、数字、下划线等)的模式:
$pattern = '/@([a-zA-Z0-9_]+)/';
替换为可点击链接
将匹配到的 @用户 替换为 HTML 链接,指向用户个人页面:
$text = "Hello @user1, how are you? @user2 is also here.";
$replacedText = preg_replace_callback($pattern, function($matches) {
return '<a href="/profile/' . $matches[1] . '">@' . $matches[1] . '</a>';
}, $text);
提取所有被 @ 的用户
如果需要获取文本中所有被 @ 的用户名列表:
preg_match_all($pattern, $text, $matches);
$mentionedUsers = $matches[1]; // 包含所有被 @ 的用户名数组
发送通知
当检测到 @用户 时,可以给被提及的用户发送通知:
foreach ($mentionedUsers as $username) {
// 查询数据库获取用户ID
$userId = getUserIDByUsername($username);
if ($userId) {
sendNotification($userId, "You were mentioned in a post");
}
}
数据库存储处理
存储内容时,可以选择存储原始文本或处理后的HTML:
// 存储原始文本
$db->insert('posts', [
'content' => $text,
'mentions' => json_encode($mentionedUsers)
]);
// 或存储处理后的HTML
$db->insert('posts', [
'content' => $replacedText,
'mentions' => json_encode($mentionedUsers)
]);
安全性考虑
处理用户输入时应注意防范XSS攻击:
$text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
$replacedText = preg_replace_callback($pattern, function($matches) {
$username = htmlspecialchars($matches[1], ENT_QUOTES, 'UTF-8');
return '<a href="/profile/' . $username . '">@' . $username . '</a>';
}, $text);
性能优化
对于大量文本处理,可以考虑以下优化:
// 先检查是否包含@符号再执行正则
if (strpos($text, '@') !== false) {
$replacedText = preg_replace_callback($pattern, $callback, $text);
}
完整示例
结合上述所有步骤的完整示例:
function processMentions($text) {
$pattern = '/@([a-zA-Z0-9_]+)/';
$text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
if (strpos($text, '@') !== false) {
// 替换为链接
$processedText = preg_replace_callback($pattern, function($matches) {
$username = htmlspecialchars($matches[1], ENT_QUOTES, 'UTF-8');
return '<a href="/profile/' . $username . '">@' . $username . '</a>';
}, $text);
// 获取被@用户
preg_match_all($pattern, $text, $matches);
$mentionedUsers = array_unique($matches[1]);
return [
'processed_text' => $processedText,
'mentions' => $mentionedUsers
];
}
return [
'processed_text' => $text,
'mentions' => []
];
}






