利用PHP怎么将文本中的URL转换为auolink()函数

发布时间:2021-01-14 15:02:15 作者:Leah
来源:亿速云 阅读:129

这篇文章将为大家详细讲解有关利用PHP怎么将文本中的URL转换为auolink()函数,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

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

关于利用PHP怎么将文本中的URL转换为auolink()函数就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. PHP日期函数常用日期获取方法有哪些
  2. php通过thrift操作hbase

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php auolink()

上一篇:怎么在php项目中实现动态调用

下一篇:php中ini配置的原理是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》