我需要將包含長URL的文本字符串轉換為相同的字符串,但帶有TinyURL(使用TinyURL API)。例如。轉換 blah blah blah http://example.com/news/sport blah blah blah 進入 blah blah blah http://example.com/news/sport blah blah blah 如何做到這一點? 為了縮短文本中任意數量的URL,請將推薦答案放在一個函數中,該函數接受長URL并返回短URL。然后通過PHP的preg_replace_callback函數將該函數應用于您的文本。如下所示: <?php function shorten_url($matches) { // EDIT: the preg function will supply an array with all submatches $long_url = $matches[0]; // API stuff here... $url = "http://tinyurl.com/api-create.php?url=$long_url"; return file_get_contents($url); } $text = 'I have a link to http://www.example.com in this string'; $textWithShortURLs = preg_replace_callback('|http://([a-z0-9?./=%#]{1,500})|i', 'shorten_url', $text); echo $textWithShortURLs; ?> 不要太依賴該模式,只是在沒有任何測試的情況下即時編寫它,也許其他人可以提供幫助。 請參見http://php.net/preg-replace-callback |
免責聲明:本站部分文章和圖片均來自用戶投稿和網絡收集,旨在傳播知識,文章和圖片版權歸原作者及原出處所有,僅供學習與參考,請勿用于商業用途,如果損害了您的權利,請聯系我們及時修正或刪除。謝謝!
始終以前瞻性的眼光聚焦站長、創業、互聯網等領域,為您提供最新最全的互聯網資訊,幫助站長轉型升級,為互聯網創業者提供更加優質的創業信息和品牌營銷服務,與站長一起進步!讓互聯網創業者不再孤獨!
掃一掃,關注站長網微信