其實我在《把文本中的URL地址轉換為可點選連結的JavaScript、PHP自訂函數》一文中介紹過PHP代碼如何?將URL地址轉化成連結的方法,今天給大家介紹一個更加簡潔的版本,先來看看PHP的原始碼:
auolink() API
複製代碼 代碼如下:
/**
* 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>
?>
怎麼樣,方便好用吧!