0

我经常在我的 WordPress 构建中使用以下代码,以帮助防止添加无效链接:

// add http:// if necessary
function addHttp($url) {
    if(substr($url, 0, 4) == 'www.') {
        $url = 'http://' . $url;
    }
    return $url;
}

但如果有人添加包含“http://”但包含“www”的链接,这将不起作用。也在里面。

有谁知道我可以如何修改我的脚本来满足这个要求?

4

2 回答 2

7
  1. 不要假设 URL 将包含www在其中。添加它通常会破坏 URL。
  2. 测试它是否以httpor开头,https如果不是则添加方案

所以:

function addHttp($url) {
  if(substr($url, 0, 4) != 'http') {
    $url = 'http://' . $url;
  }
  return $url;
}
于 2013-08-31T15:06:46.317 回答
-5

您需要检查这一点,然后处理该案例,就像您已经为您处理的案例所做的那样。

我通常建议使用URL 处理NetUrl2,因为它使此类任务非常容易。

但是,您可以进行以下修改,这不仅可以规范您未涵盖的其他部分,还可以正确检查该方案。我已经突出显示了添加www.您要求的部分,因此如果您不再需要它,您可以轻松删除它:

function addHttp($url) {
    $parts = parse_url($url);

    $modif = function ($key, $prefix, $default = '') use (&$parts)
    {
        $parts[$key] = isset($parts[$key]) ? $prefix . $parts[$key] : $default;
    };

    $modif('scheme', '', 'http');
    $parts['scheme'] = strtolower($parts['scheme']);

    if (isset($parts['path']) && $parts['path'][0] !== '/')
    {
        $pathIsInPath  = strstr($parts['path'], '/', TRUE);
        $parts['host'] = $pathIsInPath ? : (isset($parts['host']) ? $parts['host'] : '') . $parts['path'];
        $parts['path'] = $pathIsInPath ? substr($parts['path'], strlen($pathIsInPath)) : '';
    }

    if (isset($parts['port']) && $parts['scheme'] === getservbyport($parts['port'], 'tcp')) {
        unset($parts['port']);
    }

    $modif('path', '', '/');
    $parts['path'] === '/' && $parts['path'] = '';

    // add www. if wanted
    if (substr($parts['host'], 0, 4) !== 'www.') {
        $modif('host', 'www.');
    }

    return sprintf('%s://%s%s%s%s%s', $parts['scheme'], $parts['host'], $modif('port', ':')
        , $parts['path'], $modif('query', '?'), $modif('fragment', '#'));
}
于 2013-08-31T15:06:32.080 回答