Home > Backend Development > PHP Tutorial > PHP实现把文本中的URL转换为链接的函数

PHP实现把文本中的URL转换为链接的函数

WBOY
Release: 2016-06-20 13:03:25
Original
970 people have browsed it

/**
* 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(&#39;`([^"=\&#39;>])((http|https|ftp|ftps)://[^\s< ]+[^\s<\.)])`i&#39;, &#39;$1<a href="$2" rel="external nofollow" &#39;.$attrs.&#39;>$2</a>&#39;, $str);
$str = substr($str, 1);
return $str;
}
Copy after login

怎么样,很简洁吧!看看函数的API文档吧:

语法

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

参数介绍

str – 必选(String 类型数据)。需要查询替换的文本。
attributes -可选(Array 类型数据)。替换链接的一些可选参数。

返回值

返回替换后的文本。

autolink() 调用方法

autolink使用起来也很方便,我们可以只传一个参数,即为必选的需要替换的字符文本。例如:

<?php
$str = &#39;A link : http://example.com/?param=value#anchor.&#39;;
$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>.
?>
Copy after login

另外我们还可以设置一些额外的链接的参数,可以让生成的链接在新窗口中打开,或者不希望搜索引擎索引替换的链接。例如:

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

 


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template