PHP如何?把文本中的URL轉換為連結

來源:互聯網
上載者:User
其實我在《把文本中的URL地址轉換為可點選連結的JavaScript、PHP自訂函數》一文中介紹過PHP代碼如何?將URL地址轉化成連結的方法,今天給大家介紹一個更加簡潔的版本,先來看看PHP的原始碼:

/*** Author: SeeDZ* From: http://code.seebz.net/p/autolink-php/**/function autolink($str, $attributes = array()) {$attrs = '';foreach ($attributes as $attribute=>$value) {$attrs .= " {$attribute}=\"{$value}\"";} $str = ' '.$str;$str = preg_replace('`([^"=\'>])((http|https|ftp|ftps)://[^\s< ]+[^\s<\.)])`i', '$1<a href="$2" rel="external nofollow" '.$attrs.'>$2</a>', $str);$str = substr($str, 1); return $str;}

怎麼樣,很簡潔吧!看看函數的API文檔吧:

文法

string autolink ( string $str [, array $attributes = array() ] )

參數介紹

str – 必選(String 類型資料)。需要查詢替換的文本。
attributes -可選(Array 類型資料)。替換連結的一些選擇性參數。

傳回值

返回替換後的文本。

autolink() 調用方法

autolink使用起來也很方便,我們可以只傳一個參數,即為必選的需要替換的字元文本。例如:

<?php $str = 'A link : http://example.com/?param=value#anchor.';$str = autolink($str);echo $str; // A link : <a href="http://example.com/?param=value#anchor" rel="external nofollow" >http://example.com/?param=value#anchor</a>.?>

另外我們還可以設定一些額外的連結的參數,可以讓產生的連結在新視窗中開啟,或者不希望搜尋引擎索引替換的連結。例如:

 <?php $str = 'http://example.com/';$str = autolink($str, array("target"=>"_blank","rel"=>"nofollow")); echo $str; // <a href="http://example.com/" rel="external nofollow" target="_blank" >http://example.com/</a> ?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.