PHP: How to use the Twitter API's data to convert URLs, mentions, and hastags in tweets to links?

后端 未结 7 603
盖世英雄少女心
盖世英雄少女心 2021-02-05 14:52

I\'m really stumped on how Twitter expects users of its API to convert the plaintext tweets it sends to properly linked HTML.

Here\'s the deal: Twitter\'s JSON API sends

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 15:08

    Here is a JavaScript version (using jQuery) of vita10gy's solution

    function tweetTextToHtml(tweet, links, users, hashtags) {
    
        if (typeof(links)==='undefined') { links = true; }
        if (typeof(users)==='undefined') { users = true; }
        if (typeof(hashtags)==='undefined') { hashtags = true; }
    
        var returnStr = tweet.text;
        var entitiesArray = [];
    
        if(links && tweet.entities.urls.length > 0) {
            jQuery.each(tweet.entities.urls, function() {
                var temp1 = {};
                temp1.start = this.indices[0];
                temp1.end = this.indices[1];
                temp1.replacement = '' + this.display_url + '';
                entitiesArray.push(temp1);
            });
        }
    
        if(users && tweet.entities.user_mentions.length > 0) {
            jQuery.each(tweet.entities.user_mentions, function() {
                var temp2 = {};
                temp2.start = this.indices[0];
                temp2.end = this.indices[1];
                temp2.replacement = '@' + this.screen_name + '';
                entitiesArray.push(temp2);
            });
        }
    
        if(hashtags && tweet.entities.hashtags.length > 0) {
            jQuery.each(tweet.entities.hashtags, function() {
                var temp3 = {};
                temp3.start = this.indices[0];
                temp3.end = this.indices[1];
                temp3.replacement = '#' + this.text + '';
                entitiesArray.push(temp3);
            });
        }
    
        entitiesArray.sort(function(a, b) {return b.start - a.start;});
    
        jQuery.each(entitiesArray, function() {
            returnStr = substrReplace(returnStr, this.replacement, this.start, this.end - this.start);
        });
    
        return returnStr;
    }
    

    You can then use this function like so ...

    for(var i in tweetsJsonObj) {
        var tweet = tweetsJsonObj[i];
        var htmlTweetText = tweetTextToHtml(tweet);
    
        // Do something with the formatted tweet here ...
    }
    

提交回复
热议问题