微博开拓之@替代

时间:2014-02-15所属栏目: PHP/PHP框架 来源: 未知 热度:

在微博开拓中,对付@的替代,许多人性德想到的是正则吧,正则除了服从题目,尚有误替代,举个例子:

@ponyma也许被理会成了"@pony"+"ma"

不多说,直接上代码:

$users['pony']      = '马化腾';
$users['ponyma']    = '坡泥马';
$users['ponyli']    = '坡泥李';
$text = "@pony:出格声明,@ponyli@ponyma@ponywong@ponylao什么的都不是我";
preg_match_all('/@\w+/', $text, $matches);
if(is_array($matches[0]) && !empty($matches[0])){
    $replaces       = array_combine($matches[0], $matches[0]);
}
foreach($users as $userid=>$username){
    $replaces['@'.$userid]  = "<a href='http://t.qq.com/{$userid}'>{$username}</a>";
}
$html               = strtr($text, $replaces);
echo $html;

功效:

<a href=’http://t.qq.com/pony’>马化腾</a>:出格声明,<a href=’http://t.qq.com/ponyli’>坡泥李</a><a href=’http://t.qq.com/ponyma’>坡泥马</a>@ponywong@ponylao什么的都不是我

标签:
评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)