2012-08-29 49 views
0

我用下面的代码只是为了任何URL来开始转换与http://https:// 不过这个功能使得问题,确切类型的网址为例parse_url YouTube的链接

$url = 'www.youtube.com/watch?v=_ss'; // url without http:// 

function convertUrl ($url){ 
$parts = parse_url($url); 
$returl = ""; 
if (empty($parts['scheme'])){ 
$returl = "http://".$parts['path']; 
} else if ($parts['scheme'] == 'https'){ 
$returl = "https://".$parts['host'].$parts['path']; 
} else { 
$returl = $url; 
} 
return $returl; 
} 

$url = convertUrl($url); 
echo $url; 

输出

http://www.youtube.com/watch 

预期的输出,因为我想

http://www.youtube.com/watch?v=_ss 

因为我主要用它来修复任何网址而没有http://所以有什么方法可以编辑这个功能,所以它可以通过=_的所有网址,如示例中所示!因为这就是URL的查询部分

$query = $parts['query']; 

:因为它真的很讨厌我了〜谢谢

+2

的'GET' PARAMS都在里面'$部件[ '查询']' – hjpotter92

回答

5

你会想。

您可以通过修改函数来做到这一点:

function convertUrl ($url){ 
    $parts = parse_url($url); 
    $returl = ""; 
    if (empty($parts['scheme'])){ 
     $returl = "http://".$parts['path']; 
    } else if ($parts['scheme'] == 'https'){ 
     $returl = "https://".$parts['host'].$parts['path']; 
    } else { 
     $returl = $url; 
    } 
    // Define variable $query as empty string. 
    $query = ''; 
    if ($parts['query']) { 
     // If the query section of the URL exists, concatenate it to the URL. 
     $query = '?' . $parts['query']; 
    } 
    return $returl . $query; 
} 
+0

完美的作品。 〜非常感谢 –

2

如果你真正关心的是通过URL的第一部分,怎么样一种替代方法?

$pattern = '#^http[s]?://#i'; 
if(preg_match($pattern, $url) == 1) { // this url has proper scheme 
    return $url; 
} else { 
    return 'http://' . $url; 
} 
+0

好吧,这真棒,聪明,会比parse_url更好地使用它。 –

2

http://codepad.org/bJ7pY8bg

<?php 
$url1 = 'www.youtube.com/watch?v=_ss'; 
$url2 = 'http://www.youtube.com/watch?v=_ss'; 
$url3 = 'https://www.youtube.com/watch?v=_ss'; 
function urlfix($url) { 
return preg_replace('/^.*www\./',"https://www.",$url); 
} 
echo urlfix($url1)."\n"; 
echo urlfix($url2),"\n"; 
echo urlfix($url3),"\n"; 

输出:

https://www.youtube.com/watch?v=_ss 
https://www.youtube.com/watch?v=_ss 
https://www.youtube.com/watch?v=_ss