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

157次阅读
没有评论
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;
}

语法

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>

?>
正文完
有偿技术支持加微信
post-qrcode
 
评论(没有评论)
验证码