欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP实现把文本中的URL转换为链接的auolink()函数分享

程序员文章站 2022-11-14 18:06:14
其实我在《把文本中的url地址转换为可点击链接的javascript、php自定义函数》一文中介绍过php代码如何实现将url地址转化成链接的方法,今天给大家介绍一个更加简...

其实我在《把文本中的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>
 
?>

怎么样,方便好用吧!