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

后端 未结 7 604
盖世英雄少女心
盖世英雄少女心 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

    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.

    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.

    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"] = "".$e->display_url."";
                $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"] = "@".$e->screen_name."";
                $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"] = "#".$e->text."";
                $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);
    }
    
    
    ?>
    

提交回复
热议问题