PHP: Properly convert addresses to clickeable link

2019-02-16 05:11发布

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.

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.

to:

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

The question is how to do this (with ereg_replace?) instead of using tons of lines of code.

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!

1条回答
倾城 Initia
2楼-- · 2019-02-16 05:23

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.

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

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

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

And here is the code

$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>';
}
查看更多
登录 后发表回答