PHP Twitter replace link and hashtag with real link

前端 未结 4 1206
温柔的废话
温柔的废话 2020-12-18 13:07

I am looping over JSON response from Twitter API. Each API response gives me a tweet similar to:

Hi my name is @john, and I love #soccer, visit me

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 13:37

    Heres the function which converts hashtags, user mentions and urls to links, using 'entities' data on a tweet from Twitter API.

    #Google#%1$s', $hash, urlencode($hash)), $text);
        }
    
        // user_mentions
        $linkified = array();
        foreach ($tweet['entities']['user_mentions'] as $userMention) {
            $name = $userMention['name'];
            $screenName = $userMention['screen_name'];
    
            if (in_array($screenName, $linkified)) {
                continue; // do not process same user mention twice or more
            }
            $linkified[] = $screenName;
    
            // replace single words only, so looking for @John we wont linkify >@John@%1$s', $screenName, $name), $text);
        }
    
        // urls
        $linkified = array();
        foreach ($tweet['entities']['urls'] as $url) {
            $url = $url['url'];
    
            if (in_array($url, $linkified)) {
                continue; // do not process same url twice or more
            }
            $linkified[] = $url;
    
            $text = str_replace($url, sprintf('%1$s', $url), $text);
        }
    
        return $text;
    }
    

提交回复
热议问题