PHP实现微博的@好友和话题功能
DATE: 2017-03-28 / VIEWS: 1522
<?php
$post_content = "@jb哈哈:51和@twitter@在研究用#P H P#的#正则表达式#过 滤话题和<i></i>对象名";
// 过滤多空格,转化HTML代码
$post_content = preg_replace(['/(\s+)/', '/@/', '/</', '/>/'], [' ', ' @', '<', '>'], $post_content);
// 标签正则
$tag_pattern = "/\#([^\#|.]+)\#/";
// 用户正则
$user_pattern = "/@([^\r\n]*?)[:|:|,|,|#|\s]/i";
// 提取用户
preg_match_all($user_pattern, $post_content, $userArr);
// 处理用户
$test = $re = [];
foreach ($userArr[1] as $key => $user) {
if (strlen($user) < 30 && $key < 3) {
$test[] = "/@{$user}/";
$re[] = "<a href='a.php?id={$user}''>@{$user}</a>";
}
}
// 处理正文
$post_content = preg_replace($test, $re, $post_content);
$post_content = preg_replace($tag_pattern, '<a href="http://twitter.com/search?q=#${1}">#${1}#</a>', $post_content, 1);
// 输出
echo trim($post_content);