javascript - php如何将字符串的网址替换成a标签,求完善

查看:78
本文介绍了javascript - php如何将字符串的网址替换成a标签,求完善的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

    $url = "软件下载网址:http://www.abc.com/vip/xz/ 【视频教程:www.abc.com/vip/  】  地址:baidu.com 地址:www2.baidu.com 售后QQ群:544654";

    $result = rep_url($url);

    /**
     * 将字符串的url转化成可以点击的
     * @date   2017-06-10T21:00:55+0800
     */
    function rep_url($str){
        $result = preg_match('/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i',$str,$data);
        if (is_array($data) == true && $result > 0) {
            foreach ($data as $key => $value) {
                $str = str_replace($value,"<a style='text-decoration: none;outline: none;color: #FF5722;' target='_blank' href='$value'>$value</a>",$str);
            }
            // "<a style='text-decoration: none;outline: none;color: #FF5722;' target='_blank' href='$0'>$0</a>"
        }
        return $str;
    }

执行结果如下(只有第一个被替换了):

其他类型的url怎么才能替换,本人实在不熟正则望各位指教。

解决方案

<?php

$re = '/(http|https|ftp)?(?::\/\/)?(?:\w+)(?=\.)(?:[\w\.]+)(?:[\w&?+=\/]+)?/';
$str = '软件下载网址:http://www.abc.com/vip/xz/ 【视频教程:http://pan.baidu.com/share/link?shareid=143406171&uk=746154028  】  地址:baidu.com/?a=55&b=33 地址:www2.baidu.com 售后QQ群:544654';

$output = preg_replace_callback($re, function($matches) {
    if (!empty($matches[1]) and in_array($matches[1], ['http', 'https', 'ftp'])) {
        return sprintf('<a href="%s">%s</a>', $matches[0], $matches[0]);
    } else {
        return sprintf('<a href="%s%s">%s</a>', 'http://', $matches[0], $matches[0]);
    }
}, $str);

print $output;

output:

软件下载网址:<a href="http://www.abc.com/vip/xz/">http://www.abc.com/vip/xz/</a> 【视频教程:<a href="http://pan.baidu.com/share/link?shareid=143406171&uk=746154028">http://pan.baidu.com/share/link?shareid=143406171&uk=746154028</a>  】  地址:<a href="http://baidu.com/?a=55&b=33">baidu.com/?a=55&b=33</a> 地址:<a href="http://www2.baidu.com">www2.baidu.com</a> 售后QQ群:544654

今天刚好讲了个正则表达式的讲堂, 回放已经出来了, 欢迎观看...
https://segmentfault.com/l/15...

这篇关于javascript - php如何将字符串的网址替换成a标签,求完善的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆