跪求正则表达式写法

koueing 2015-10-13 05:10:58
在线求助php正则表达式写法。
以下文本中出现的所有url想换成超链接形式。

“文字www.baidu.com文字
www.html.com
文字http://www.baidu.com
https://www.google.com”

代码如下:
public function make_clickable($str) {
$str = preg_replace('`([^"=\'>])((http://|https://|ftp://|ftps://|www.)[^\s< ]+[^\s<\.)])`i', '$1<a href="$2" target="_blank" rel="nofollow">$2</a>', $str);
return $str;
}

问题:
当文本为www.baidu.com时,超链接变成http://localhost/www.baidu.com

www前没有http或https的情况下,想替换成http://www.baidu.com的格式,再替换成超链接,
跪求正则表达式写法。
...全文
66 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
koueing 2015-10-13
  • 打赏
  • 举报
回复
<?php

class Convert
{
/*
* URLを自動でリンク形式に
*/
public function make_clickable($str)
{

$str = preg_replace('`([^"=\'])((http://|https://|ftp://|ftps://|www.)[^\s< ]+[^\s<\.)])`ie', "self::_link('\\1','\\2')", $str);
return $str;

}

private static function _link($text, $link)
{
if (explode('.', $link)[0] == 'www') {

$link = 'http://' . $link;

}
return $text . '<a href="' . $link . '" target="_blank" rel="nofollow">' . $link . '</a>';
}
}
koueing 2015-10-13
  • 打赏
  • 举报
回复
非常有用。感谢
果酱很好吃 2015-10-13
  • 打赏
  • 举报
回复
在此基础上改了下

$s = '“文字www.baidu.com文字
www.html.com
文字http://www.baidu.com
https://www.google.com”';

echo make_clickable($s);
function make_clickable($str) {
$str = preg_replace('`([^"=\'>])((http://|https://|ftp://|ftps://|www.)[^\s< ]+[^\s<\.)])`ie',"_link('\\1','\\2')" , $str);
return $str;
}
function _link($text,$link){
if(explode('.',$link)[0]=='www'){
$link='http://'.$link;
}
return $text.'<a href="'.$link.'" target="_blank" rel="nofollow">'.$link.'</a>';
}

21,886

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧