PHP:如何使用 Twitter API 的数据将推文中的 URL、提及和标签转换为链接? [英] PHP: How to use the Twitter API's data to convert URLs, mentions, and hastags in tweets to links?

查看:32
本文介绍了PHP:如何使用 Twitter API 的数据将推文中的 URL、提及和标签转换为链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很困惑 Twitter 希望其 API 的用户如何将其发送的纯文本推文转换为正确链接的 HTML.

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

事情是这样的:当您请求推文的详细数据时,Twitter 的 JSON API 会将这组信息发回:

Here's the deal: Twitter's JSON API sends this set of information back when you request the detailed data for a tweet:

{
    "created_at":"Wed Jul 18 01:03:31 +0000 2012",
    "id":225395341250412544,
    "id_str":"225395341250412544",
    "text":"This is a test tweet. #boring @nbc http://t.co/LUfDreY6 #skronk @crux http://t.co/VpuMlaDs @twitter",
    "source":"web",
    "truncated":false,
    "in_reply_to_status_id":null,
    "in_reply_to_status_id_str":null,
    "in_reply_to_user_id":null,
    "in_reply_to_user_id_str":null,
    "in_reply_to_screen_name":null,
    "user": <REDACTED>,
    "geo":null,
    "coordinates":null,
    "place":null,
    "contributors":null,
    "retweet_count":0,
    "entities":{
        "hashtags":[
            {
                "text":"boring",
                "indices":[22,29]
            },
            {
                "text":"skronk",
                "indices":[56,63]
            }
        ],
        "urls":[
            {
                "url":"http://t.co/LUfDreY6",
                "expanded_url":"http://www.twitter.com",
                "display_url":"twitter.com",
                "indices":[35,55]
            },
            {
                "url":"http://t.co/VpuMlaDs",
                "expanded_url":"http://www.example.com",
                "display_url":"example.com",
                "indices":[70,90]
            }
        ],
        "user_mentions":[
            {
                "screen_name":"nbc",
                "name":"NBC",
                "id":26585095,
                "id_str":"26585095",
                "indices":[30,34]
            },
            {
                "screen_name":"crux",
                "name":"Z. D. Smith",
                "id":407213,
                "id_str":"407213",
                "indices":[64,69]
            },
            {
                "screen_name":"twitter",
                "name":"Twitter",
                "id":783214,
                "id_str":"783214",
                "indices":[91,99]
            }
        ]
    },
    "favorited":false,
    "retweeted":false,
    "possibly_sensitive":false
}

对于这个问题,有趣的部分是 text 元素和 hashtagsuser_mentionsurls 中的条目 数组.Twitter 告诉我们标签、提及和 url 在 text 元素中的哪个位置与 indices 数组一起出现......所以这里是问题的关键:

The interesting parts, for this question, are the text element and the entries in the hashtags, user_mentions, and urls arrays. Twitter is telling us where in the text element the hastags, mentions, and urls appear with the indices arrays... so here's the crux of the question:

你如何使用那些索引数组?

您不能通过使用诸如 之类的东西在每个链接元素上循环来直接使用它们substr_replace,因为替换text 中的第一个链接元素将使后续链接元素的所有索引值无效.您也不能使用 substr_replace 的数组功能,因为它仅在您为第一个 arg 提供一个字符串数组而不是单个字符串时才有效(我已经测试过了.结果……很奇怪).

You can't just use them straight up by looping over each link element with something like substr_replace, since replacing the first link element in the text will invalidate all the index values for subsequent link elements. You also can't use substr_replace's array functionality, since it only works when you give it an array of strings for the first arg, rather than a single string (I've tested this. The results are... strange).

有没有什么函数可以同时用不同的替换字符串替换单个字符串中的多个索引分隔的子字符串?

Is there some function that can simultaneously replace multiple index-delimited substrings in a single string with different replacement strings?

推荐答案

要使用 twitter 直接提供的索引,您只需通过简单的替换就可以收集您想要进行的替换,然后将它们向后排序.你可能会找到一种更聪明的方法来构建 $entities,无论如何我希望它们是可选的,所以我就这样亲吻了.

All you have to do to use the indices twitter provides straight up with a simple replace is collect the replacements you want to make and then sort them backwards. You can probably find a more clever way to build $entities, I wanted them optional anyway, so I KISS as far as that went.

无论如何,我在这里的目的只是为了表明您不需要分解字符串和字符数等等.不管你怎么做,你需要做的就是从字符串的末尾开始,一直工作到字符串的开头,而 twitter 的索引仍然有效.

Either way, my point here was just to show that you don't need to explode the string and character count and whatnot. Regardless of how you do it, all you need to to is start at the end and work to the beginning of the string, and the index twitter has is still valid.

<?php 

function json_tweet_text_to_HTML($tweet, $links=true, $users=true, $hashtags=true)
{
    $return = $tweet->text;

    $entities = array();

    if($links && is_array($tweet->entities->urls))
    {
        foreach($tweet->entities->urls as $e)
        {
            $temp["start"] = $e->indices[0];
            $temp["end"] = $e->indices[1];
            $temp["replacement"] = "<a href='".$e->expanded_url."' target='_blank'>".$e->display_url."</a>";
            $entities[] = $temp;
        }
    }
    if($users && is_array($tweet->entities->user_mentions))
    {
        foreach($tweet->entities->user_mentions as $e)
        {
            $temp["start"] = $e->indices[0];
            $temp["end"] = $e->indices[1];
            $temp["replacement"] = "<a href='https://twitter.com/".$e->screen_name."' target='_blank'>@".$e->screen_name."</a>";
            $entities[] = $temp;
        }
    }
    if($hashtags && is_array($tweet->entities->hashtags))
    {
        foreach($tweet->entities->hashtags as $e)
        {
            $temp["start"] = $e->indices[0];
            $temp["end"] = $e->indices[1];
            $temp["replacement"] = "<a href='https://twitter.com/hashtag/".$e->text."?src=hash' target='_blank'>#".$e->text."</a>";
            $entities[] = $temp;
        }
    }

    usort($entities, function($a,$b){return($b["start"]-$a["start"]);});


    foreach($entities as $item)
    {
        $return = substr_replace($return, $item["replacement"], $item["start"], $item["end"] - $item["start"]);
    }

    return($return);
}


?>

这篇关于PHP:如何使用 Twitter API 的数据将推文中的 URL、提及和标签转换为链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆