簡體   English   中英

如何使用PHP preg_replace鏈接Twitter用戶名?

[英]How do I linkify Twitter usernames using PHP preg_replace?

我想搜索我的twitter狀態對象的text屬性,並用@username替換為<a href="http:/twitter.com/username">@username</a> 到目前為止,我嘗試過的內容如下:

$pattern = '/([@]{1})([a-zA-Z0-9\_]+)/';
$replace = '<a href="http://twitter.com/\2">\1\2</a>';
$new_string = preg_replace($pattern, $replace, $text);

但是它沒有任何替代。 我知道我的reg exp是錯誤的,但是我不知道確切的位置/原因。 救命?

**編輯:...根據要求提供樣本數據?

$text = '@janesmith I like that, but my friend @johndoe said it better.';

所需的輸出:

@janesmith我喜歡,但是我的朋友@johndoe說的更好。

***** MY FULL FUNCTION *****

function linkify($string, $twitter=false) {

    // reg exp pattern
    $pattern = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

    // convert string URLs to active links
    $new_string = preg_replace($pattern, "<a href=\"\\0\">\\0</a>", $string);

    if ($twitter) {
        $pattern = '/@([a-zA-Z0-9_]+)/';
        $replace = '<a href="http://twitter.com/\1">@\1</a>';
        $new_string = preg_replace($pattern, $replace, $new_string);
    }

    return $new_string;
}

為什么_之前有\\ 如果您將\\取出,是否可行? 雖然這不應該破壞功能...

\\1更改為\\\\1可能會有所幫助,這樣可以確保反斜杠已轉義。 或更高(自PHP 4.0.4起) $1 但是同樣,它應該按原樣使用單引號引起來。

另外,您可以簡化:

$pattern = '/@([a-zA-Z0-9_]+)/';
$replace = '<a href="http://twitter.com/$1">@$1</a>';

我也更新了一些功能來支持主題標簽:

函數linkify($ string,$ twitter = false){

// reg exp模式

$ pattern =“ /(http|https|ftp|ftps)\\:\\/\\/[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(\\/\\S *)?/“;

//將字符串URL轉換為活動鏈接$ new_string = preg_replace($ pattern,“ \\ 0”,$ string);

如果($ twitter){

  $pattern = '/\\@([a-zA-Z0-9_]+)/'; $replace = '<a href="http://twitter.com/\\1">@\\1</a>'; $new_string = preg_replace($pattern, $replace, $new_string); $pattern = '/\\#([a-zA-Z0-9_]+)/'; $replace = '<a href="http://twitter.com/search/#\\1">#\\1</a>'; $new_string = preg_replace($pattern, $replace, $new_string); 

}

返回$ new_string; }

發現此方法適用於URL,@ usernames和#hashtags:

http://davidwalsh.name/linkify-twitter-feed

Twitter更新了他們的api,至少對我來說,這更加用戶友好。 查閱位於dev.twitter.com/docs/twitter-for-websites上的文檔, 單擊此處 您必須首先創建一個應用程序,按照分步說明進行操作,然后再創建一個小部件。 您在下面看到的小部件顯示了我的推文,但您可以創建一個小工具,以顯示時間軸上的所有操作或搜索,列表等的結果...

     <a class="twitter-timeline" ref="https://twitter.com/SKAmerica" data-widget-id="359949405157203970">Tweets by @SKAmerica</a>
     <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id))js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM