溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

利用PHP怎么將文本中的URL轉(zhuǎn)換為auolink()函數(shù)

發(fā)布時間:2021-01-14 15:02:15 來源:億速云 閱讀:135 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)利用PHP怎么將文本中的URL轉(zhuǎn)換為auolink()函數(shù),文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

auolink() API

復(fù)制代碼 代碼如下:


/**
* 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;
}

怎么樣,很簡潔吧!看看函數(shù)的API文檔吧:

語法

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

參數(shù)介紹

str – 必選(String 類型數(shù)據(jù))。需要查詢替換的文本。
attributes -可選(Array 類型數(shù)據(jù))。替換鏈接的一些可選參數(shù)。

返回值

返回替換后的文本。

autolink() 調(diào)用方法

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

復(fù)制代碼 代碼如下:


<?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>.
 
?>

另外我們還可以設(shè)置一些額外的鏈接的參數(shù),可以讓生成的鏈接在新窗口中打開,或者不希望搜索引擎索引替換的鏈接。例如:

復(fù)制代碼 代碼如下:


<?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>
 
?>

關(guān)于利用PHP怎么將文本中的URL轉(zhuǎn)換為auolink()函數(shù)就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI