2013-10-14 32 views
3

我目前正在使用一個簡短的url腳本來處理twitter。php用全新的url替換字符串中的網址

目前我正在將我想要的tweet文本輸入到一個長URL的textarea中。到目前爲止,我已經檢測的網址如下:

$regex = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 
if (preg_match($regex, $text, $url)) { // $url is now the array of urls 
    echo $url[0]; 
} 

當進入一個鳴叫它會是這個樣子:

hi here is our new product, check it out: www.mylongurl.com/this-is-a-very-long-url-and-needs-to-be-shorter 

我然後產生一些隨機字符追加在結束一個新的網址,所以它最終會是這樣的:shorturl.com/ghs7sj。

,當點擊,shorturl.com/ghs7sj它重定向你www.mylongurl.com/this-is-aver-long-url-and-needs-to-be-shorter。這一切工作正常。

我的問題是tweet文本仍然包含很長的url。有沒有一種方法,我可以用短的替換長網址?我需要一些新的代碼嗎?或者我可以適應上述也做到這一點?

我想要的結果是這樣的:

hi here is our new product, check it out: shorturl.com/ghs7sj 

這是基於WordPress因此所有信息當前存儲在帖子和post_meta表。請注意,推文中只會有1個網址。

+0

你有API可以縮短你的網址。 https://developers.google.com/url-shortener/v1/getting_started或http://to.ly/api_info.php或... –

+0

嗨,我知道這一點,但會有很多自定義功能添加在大多數API不提供 – danyo

回答

3

可你只需要使用PHP的str_replace()功能?像

str_replace($url, $short_url, $text); 
+2

$ url [0]的準確日後。 –

1

您可以通過使用preg_replace_callback()做一個回調函數內更換:

$regex = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 
$text = preg_replace_callback($regex, function($url) { 
    // do stuff with $url[0] here 
    return make_short_url($url[0]); 
}, $text);