2010-09-26 93 views
3

我正在從Twitter API循環JSON響應。每個API響應給了我類似的tweet:PHP Twitter替換鏈接和與真實鏈接的hashtag

大家好,我是@約翰,我愛#soccer,請訪問我

我試圖取代@john,並插入<a href=http://twitter.com/john>@john</a>但逗號(,@john後,是問題所在。

如何在標籤之前和之後替換點,逗號等?

回答

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

對不起,SO沒有通知我有人已經發布了答案。 – racetrack 2010-09-26 19:41:35

+0

這不會完全工作,它會忽略#標籤中的'.' ... – Legionar 2017-11-06 17:33:13

3
preg_replace("/@(\w+)/", "<a href=http://twitter.com/$1>@$1</a>", $string)" 
4

要做到主題標籤做它轉換主題標籤這個

$item_content = preg_replace("/#([a-z_0-9]+)/i", "<a href=\"http://twitter.com/search/$1\">$0</a>", $item_content); 
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; 
} 
+0

正是我需要的感謝! – 2014-07-25 18:36:09

+0

@DominicTobias這裏有一個更新版本 - https://github.com/alanbem/tweets2feed/blob/master/app/app.php#L34 – 2014-09-01 23:03:26