PHP Twitter用真实链接替换链接和主题标签

gbv*_*cbg 3 php api twitter

我正在循环来自Twitter API的JSON响应.每个API响应都给我一条类似于以下内容的推文:

嗨,我的名字是@john,我喜欢#soccer,拜访我

我试图替换@john,并插入<a href=http://twitter.com/john>@john</a>但后面的逗号(,)@john,是问题.

如何在标签之前和之后替换点,逗号等?

Tim*_*per 11

$str = preg_replace("/@(\w+)/i", "<a href=\"http://twitter.com/$1\">$0</a>", $str);
Run Code Online (Sandbox Code Playgroud)


Ala*_*Bem 9

继承了使用来自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;
}
Run Code Online (Sandbox Code Playgroud)