且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP:将地址正确转换为字符串中的可点击链接

更新时间:2023-02-23 09:16:29

第一条建议,远离 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>';
}