• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

PHP如何实现把文本中的URL转换为链接

php 搞代码 3年前 (2022-01-22) 10次浏览 已收录 0个评论

其实我在《把文本中的URL地址转换为可点击链接的JavaScript、PHP自定义函数》一文中介绍过PHP代码如何实现将URL地址转化成链接的方法,今天给大家介绍一个更加简洁的版本,先来看看PHP的源代码:

/*** 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<div style="color:transparent">本&文来源gaodai^.ma#com搞#代!码网</div><strong>搞gaodaima代码</strong>#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转换为链接的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP如何实现把文本中的URL转换为链接

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址