我经常在WordPress构建中使用以下代码,以帮助防止添加无效链接:
// add http:// if necessary
function addHttp($url) {
if(substr($url, 0, 4) == 'www.') {
$url = 'http://' . $url;
}
return $url;
}
但是,如果有人添加了一个包含"http://"但不包含"www."的链接,这将不起作用里面也有。
有人知道我如何修改我的脚本来满足这个需求吗?
- 不要以为URL中会有
www
。添加它通常会破坏URL - 测试它是否以
http
或https
开头,如果不是,则添加方案
因此:
function addHttp($url) {
if(substr($url, 0, 4) != 'http') {
$url = 'http://' . $url;
}
return $url;
}
您需要检查这一点,然后处理该案例,就像您已经处理的案例一样。
我通常建议使用NetUrl2
类来处理URL,因为它使此类任务变得非常容易。
然而,您只需进行以下修改,不仅可以对您未涵盖的其他部分进行规范化,还可以对方案进行适当检查。我已经强调了添加了你要求的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', '#'));
}