PHP Twitter replace link and hashtag with real link

前端 未结 4 1195
温柔的废话
温柔的废话 2020-12-18 13:07

I am looping over JSON response from Twitter API. Each API response gives me a tweet similar to:

Hi my name is @john, and I love #soccer, visit me

相关标签:
4条回答
  • 2020-12-18 13:25

    To do hash-tags do this

    $item_content = preg_replace("/#([a-z_0-9]+)/i", "<a href=\"http://twitter.com/search/$1\">$0</a>", $item_content);
    
    0 讨论(0)
  • 2020-12-18 13:36
    $str = preg_replace("/@(\w+)/i", "<a href=\"http://twitter.com/$1\">$0</a>", $str);
    
    0 讨论(0)
  • 2020-12-18 13:37

    Heres the function which converts hashtags, user mentions and urls to links, using 'entities' data on a tweet from Twitter API.

    <?php
    
    function tweet_html_text(array $tweet) {
        $text = $tweet['text'];
    
        // hastags
        $linkified = array();
        foreach ($tweet['entities']['hashtags'] as $hashtag) {
            $hash = $hashtag['text'];
    
            if (in_array($hash, $linkified)) {
                continue; // do not process same hash twice or more
            }
            $linkified[] = $hash;
    
            // replace single words only, so looking for #Google we wont linkify >#Google<Reader
            $text = preg_replace('/#\b' . $hash . '\b/', sprintf('<a href="https://twitter.com/search?q=%%23%2$s&src=hash">#%1$s</a>', $hash, urlencode($hash)), $text);
        }
    
        // user_mentions
        $linkified = array();
        foreach ($tweet['entities']['user_mentions'] as $userMention) {
            $name = $userMention['name'];
            $screenName = $userMention['screen_name'];
    
            if (in_array($screenName, $linkified)) {
                continue; // do not process same user mention twice or more
            }
            $linkified[] = $screenName;
    
            // replace single words only, so looking for @John we wont linkify >@John<Snow
            $text = preg_replace('/@\b' . $screenName . '\b/', sprintf('<a href="https://www.twitter.com/%1$s" title="%2$s">@%1$s</a>', $screenName, $name), $text);
        }
    
        // urls
        $linkified = array();
        foreach ($tweet['entities']['urls'] as $url) {
            $url = $url['url'];
    
            if (in_array($url, $linkified)) {
                continue; // do not process same url twice or more
            }
            $linkified[] = $url;
    
            $text = str_replace($url, sprintf('<a href="%1$s">%1$s</a>', $url), $text);
        }
    
        return $text;
    }
    
    0 讨论(0)
  • 2020-12-18 13:38
    preg_replace("/@(\w+)/", "<a href=http://twitter.com/$1>@$1</a>", $string)"
    
    0 讨论(0)
提交回复
热议问题