LoginSignup
1
0

More than 5 years have passed since last update.

twitter api の t.co を元のURLに戻す

Last updated at Posted at 2017-11-14

TwitterAPIの返り値が、
http://yahoo.co.jphttp://t.co....になっていたりする。
もちろんURLすべて短縮されて返ってくる。

これじゃ画像かURLかもわからないので、元に戻す。


//一般的な search/tweets の結果
$res =  $this->client->get("search/tweets",$option);


foreach ($res as $key => $v) {


//            url を t.co から 元に戻す
            foreach ($v->entities->urls as $s) {
                $v->text = str_replace(
                    $s->url,
                    '<a href="'.$s->expanded_url.'">'.$s->display_url.'</a>',
                    $v->text);
            }

//            hashtagにリンクをつける
            foreach ($v->entities->hashtags as $s) {

                //https://twitter.com/freemanrepo
                $v->text = str_replace(
                    "#".$s->text,
                    '<a href="https://twitter.com/hashtag/'.$s->text.'?src=hash">#'.$s->text.'</a>',
                    $v->text);
            }


//            メンションにリンクをつける
            foreach ($v->entities->user_mentions as $s) {

                $v->text = str_replace(
                    "@".$s->screen_name,
                    '<a href="https://twitter.com/'.$s->screen_name.'">@'.$s->screen_name.'</a>',
                    $v->text);
            }


//            メディアのURLをt.co から戻す
            if(!empty($v->entities->media)){
                foreach ($v->entities->media as $s) {
                    $v->text = str_replace(
                        $s->url,
                        '<a href="'.$s->media_url_https.'">'.$s->display_url.'</a>',
                        $v->text);
                }
            }



        }



これでURLがすべて綺麗に戻されて帰ってきます。
https://syncer.jp/Web/API/Twitter/Snippet/3/

にはindicesを使う方法が書いてありますが、
文字列検索置換のが楽なので、今回はこの方法で行います。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0