从推文中过滤用户名

时间:2012-02-10 16:48:58

标签: php regex

考虑以下字符串:

No, @Username, I did not go to the supermarket yet

我使用以下正则表达式来标记所有用户名:

$tweet = preg_replace('/@([a-z0-9_]+)/i', '{USER:$1}', $tweet);

导致:

No, {USER:UserName}, I did not go to the supermarket yet

但是,我有一个包含twitter用户的表,并且想要查找user_id以便我可以输出:

No, {USER:4324322}, I did not go to the supermarket yet

或者,如果找不到匹配的用户名,则默认输出为:

No, {USER:UserName}, I did not go to the supermarket yet

为此,我首先需要preg_match所有@usernames,查找它们,然后将正确的{label}插回到推文中。我对如何构建这个问题感到困惑。谁可以帮忙?考虑用于检查数据库中用户名的代码,如下所示:

$user = db_result(db_query("SELECT id FROM users WHERE name = '%s'", $match));
if ($user = true) { // match found
  $label = '{USER:'. $user .'}';
}
else {
  $label = '{USER:'. $match .'}';
}

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

使用preg_match_callback

示例:

$tweet = preg_match_callback("(@([a-z0-9_]+))i",function($m) {
    static $cache = Array();
    $user = $m[1];
    if( !isset($cache[$user]))
        list($cache[$user]) = db_result(db_query("SELECT id FROM users WHERE name = '%s'",$user));
    return "{USER:".($cache[$user] ? $cache[$user] : $user)."}";
},$tweet);