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

后端 未结 7 592
盖世英雄少女心
盖世英雄少女心 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 14:58

    Jeff's solution worked well with English text but it got broken when the tweet contained non-ASCII characters. This solution avoids that problem:

    mb_internal_encoding("UTF-8");
    
    // Return hyperlinked tweet text from json_decoded status object:
    function MakeStatusLinks($status) 
    {$TextLength=mb_strlen($status['text']); // Number of UTF-8 characters in plain tweet.
     for ($i=0;$i<$TextLength;$i++)
     {$ch=mb_substr($status['text'],$i,1); if ($ch<>"\n") $ChAr[]=$ch; else $ChAr[]="\n
    "; // Keep new lines in HTML tweet. } if (isset($status['entities']['user_mentions'])) foreach ($status['entities']['user_mentions'] as $entity) {$ChAr[$entity['indices'][0]] = "".$ChAr[$entity['indices'][0]]; $ChAr[$entity['indices'][1]-1].=""; } if (isset($status['entities']['hashtags'])) foreach ($status['entities']['hashtags'] as $entity) {$ChAr[$entity['indices'][0]] = "".$ChAr[$entity['indices'][0]]; $ChAr[$entity['indices'][1]-1] .= ""; } if (isset($status['entities']['urls'])) foreach ($status['entities']['urls'] as $entity) {$ChAr[$entity['indices'][0]] = "".$entity['display_url'].""; for ($i=$entity['indices'][0]+1;$i<$entity['indices'][1];$i++) $ChAr[$i]=''; } if (isset($status['entities']['media'])) foreach ($status['entities']['media'] as $entity) {$ChAr[$entity['indices'][0]] = "".$entity['display_url'].""; for ($i=$entity['indices'][0]+1;$i<$entity['indices'][1];$i++) $ChAr[$i]=''; } return implode('', $ChAr); // HTML tweet. }

提交回复
热议问题