我真的難以理解Twitter如何期望其API的用戶將其發送的明文tweets轉換爲正確鏈接的HTML。PHP:如何使用Twitter API的數據將推文中的URL,提及和hastags轉換爲鏈接?
這裏的交易:當你請求的詳細數據鳴叫Twitter的JSON API發送該組信息後面:
{
"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
元素和條目hashtags
,user_mentions
和urls
陣列。 Twitter正在告訴我們哪裏在text
元素hastags,提到和URL出現與indices
陣列......所以這裏的問題的癥結所在:
你怎麼使用那些indices
陣列?
因爲替換text
中的第一個鏈接元素將使後續鏈接元素的所有索引值無效,您不能直接在每個鏈接元素上使用substr_replace
來循環使用它們。你也不能使用substr_replace
的數組功能,因爲它只適用於你爲第一個參數給它一個字符串數組,而不是單個字符串(我已經測試過了,結果是......很奇怪)。
是否有一些函數可以在一個字符串中用不同的替換字符串同時替換多個由索引定界的子字符串?
* facepalm * ...爲什麼沒有***我想到這一點?? – CoreDumpError 2014-08-27 00:24:31
適用於我...我在頂部添加了一些額外的代碼,因爲當您檢索轉發時,它們有時會包含省略號。 Twitter建議您在這種情況下使用retweet_status及其實體:https://dev.twitter.com/overview/api/entities-in-twitter-objects#retweets – diggersworld 2014-09-15 10:33:42
哇,偉大的方法,不會想到這一點。 .. – 2015-05-08 21:31:33