在 PHP 函数中从推文中检索所有用户名

Retrieving all usernames from a tweet in a PHP function

我有这个函数,它为字符串中包含的每个@username 着色

 //color  @username
 function hashtag_links($string,$id_session) {
 preg_match_all('/@(\w+)/',$string,$matches);
 foreach ($matches[1] as $match) {
$string = str_replace("@$match", "<span class=color>@$match</span>", "$string");
 }
 return $string;
 }

虽然用户名不同(@cat、@pencil、@scubadiving)但一切都很好,但如果用户名以相同的字母开头(@cat、@caterpiller、@cattering),函数只会为在这种情况下重复字母 (@cat),怎么办?

改用preg_replace:

//color  @username
function hashtag_links($string,$id_session) {
    return preg_replace('/@(\w+)/', '<span class=color>@</span>', $string);
}

嗯……假设你有这样一个字符串:

$string='Hey there, folks! @bob, @kevin, @bobby, @keverino';

我会尝试类似的方法:

preg_replace('/(@[A-Za-z0-9]+)/','<span style="color:pink;"></span>',$string);

当然,我不知道你的用户名可以包含什么,所以你可能需要调整正则表达式。