【问题标题】:Retrieving all usernames from a tweet in a PHP function从 PHP 函数中的推文中检索所有用户名
【发布时间】:2016-09-19 02:01:45
【问题描述】:

我有这个函数,它为字符串中包含的每个@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、@catrpiller、@cattering),函数只会为重复的字母着色在这种情况下(@cat),该怎么办?

【问题讨论】:

    标签: php function twitter preg-match-all hashtag


    【解决方案1】:

    使用 preg_replace 代替:

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

    【讨论】:

      【解决方案2】:

      嗯...假设你有这样的字符串:

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

      我会尝试类似:

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

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

      【讨论】:

        猜你喜欢
        • 2011-03-04
        • 2015-01-16
        • 1970-01-01
        • 2010-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多