PHP - 将链接添加到字符串中的URL [英] PHP - Add link to a URL in a string

查看:91
本文介绍了PHP - 将链接添加到字符串中的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数会在链接前添加< a href> 标签,并且< / a>

I have a function that will add the <a href> tag before a link and </a> after the link. However, it breaks for some webpages. How would you improve this function? Thanks!

function processString($s) 
{
    // check if there is a link

    if(preg_match("/http:\/\//",$s))
    {
        print preg_match("/http:\/\//",$s);


        $startUrl =  stripos($s,"http://");

        // if the link is in between text
        if(stripos($s," ",$startUrl)){
            $endUrl = stripos($s," ",$startUrl);
        }
        // if link is at the end of string
        else {$endUrl = strlen($s);}

        $beforeUrl = substr($s,0,$startUrl);
        $url = substr($s,$startUrl,$endUrl-$startUrl);
        $afterUrl = substr($s,$endUrl);

        $newString = $beforeUrl."<a href=\"$url\">".$url."</a>".$afterUrl;

        return $newString;
    }

    return $s;
}


推荐答案

function processString($s) {
    return preg_replace('/https?:\/\/[\w\-\.!~#?&=+\*\'"(),\/]+/','<a href="$0">$0</a>',$s);
}

这篇关于PHP - 将链接添加到字符串中的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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