使用正则提取和替换微博正文中的@提及

这段时间在折腾一个的 mini 型微博,晚上遇到一个问题就是要把微博和评论正文中的 @ 提及他人转换成链接,在网络上拼拼凑凑,也算弄出来了

/*
 * 显示带有 @ 提及他人的微博正文
 */
function tweet_echo($content) {
	$content = htmlspecialchars($content);
	$pattern = '/@([x{4e00}-x{9fa5}A-Za-z0-9]*)/u';
	$replacement = '<a href="user.php?name=\1">@\1</a>';
	$content = preg_replace($pattern, $replacement, $content);
	echo $content;
	var_dump($content);
}

tweet_echo('<style>color:red;</style>测试@第一个人 @第二个人@没有空格@ @没有人名');

输出

<style>color:red;</style>测试@第一个人 @第二个人@没有空格@ @没有人名
string '&lt;style&gt;color:red;&lt;/style&gt;测试<a href="user.php?name=第一个人">@第一个人</a> <a href="user.php?name=第二个人">@第二个人</a><a href="user.php?name=没有空格">@没有空格</a><a href="user.php?name=">@</a> <a href="user.php?name=没有人名">@没有人名</a>' (length=291)

Leave a Reply

Your email address will not be published. Required fields are marked *