PHP:将地址正确转换为字符串中的可点击链接 [英] PHP: Properly convert addresses to clickeable links in string

查看:17
本文介绍了PHP:将地址正确转换为字符串中的可点击链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要自动解析一个字符串并查找是否存在指向我的网站的链接,自动将地址替换为可点击的 HTML 链接.

I need to automatically parse a string and find if a link to my site is present, automatically replace the address by a clickeable HTML link.

假设我的网站地址是 www.mysite.com + wap.mysite.com + m.mysite.com,我需要转换:

Supposing my site adresses are www.mysite.com + wap.mysite.com + m.mysite.com, I need to convert:

My pictures at m.mysite.com/user/id are great.

到:

My pictures at <a href="/user/id" target="_blank">mysite.com/user/id</a> are great.

问题是如何做到这一点(使用 ereg_replace?)而不是使用大量代码行.

请注意,结果必须是相对 URL,以便将当前协议和子域用于目标链接.如果用户在 HTTPS 版本的 m 子域中,则目标将是 HTTPS 协议的 m 子域,依此类推.只能链接到 mysite.com 的链接,任何其他链接都必须被视为普通的纯文本.提前致谢!

Notice that the result must be a relative URL, so that the current protocol and subdomain is used for the target link. If the user is in the m subdomain of the HTTPS version, the target will be the m subdomain of the HTTPS protocol and so on. Only links to mysite.com must be linked, any other links must be treated as ordinary plain text. Thanks in advance!

推荐答案

第一条建议,远离 ereg,它已经被弃用了很长时间.其次,你可以通过谷歌和实验来编造一个适合你的 preg 表达式,所以调整我这里的内容以满足你的需求.

First piece of advice, stay away from ereg, it's been deprecated for a long time. Second, you can probably google and experiment to concoct a preg expression that works well for you, so tweak what I have here to suit your needs.

我能够组合一个相当简单的正则表达式来搜索 URL.

I was able to put together a fairly simple regex pattern to search for the URLs.

preg_match("/m.mysite.com\S+/", $str, $matches);

一旦你有了 URL,我建议 parse_url 而不是正则表达式.

Once you have the URLs, I'd suggest parse_url instead of regex.

这是代码

$sSampleInput = 'My pictures at http://m.mysite.com/user/id are great.';

// Search for URLs but don't look for the scheme, we'll add that later
preg_match("/m.mysite.com\S+/", $sSampleInput, $aMatches);

$aResults = array();
foreach($aMatches as $sUrl) {
    // Tack a scheme afront the URL
    $sUrl = 'http://' . $sUrl;

    // Try validating the URL, requiring host & path
    if(!filter_var(
        $sUrl,
        FILTER_VALIDATE_URL,
        FILTER_FLAG_HOST_REQUIRED|FILTER_FLAG_PATH_REQUIRED)) {
        trigger_error('Invalid URL: ' . $sUrl . PHP_EOL);
        continue;
    } else
        $aResults[] =
            '<a href="' . parse_url($sUrl, PHP_URL_PATH) .
            '" target="_blank">' . $sUrl . '</a>';
}

这篇关于PHP:将地址正确转换为字符串中的可点击链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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