2011-03-15 69 views
2

我需要幫助更換如google.com的鏈接進入http://www.google.comPHP的preg_replace幫助

$url = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2",$url); 
$output = htmlspecialchars(urldecode($url)); 

我使用的iframe,如:

<iframe src='$url'></iframe> 

但是,如果src =「google.com 「而不是」http://google.com「它不起作用。那麼,我如何才能將google.com轉換爲http://www.google.com

回答

0
$url = "www.google.com"; 
if(!preg_match("/^https/i",$url)) 
    $url = "http://$url"; 
0

有更好的方法來做到這一點,但是這將工作:

if(!preg_match("#^http:\/\/#", $url)) { 
     $url = "http://".$url; 
} 
0
$url = 'http://' . $url; 

的simpliest可能的方式:○

0

如何檢查是否http://是對的開始它,如果不標記它?像這樣:

$url = 'google.com'; 
if (!preg_match('#^http://#', $url)) { 
    $url = 'http://'.$url; 
} 
0

只是爲了好玩,這裏是一個通過採取消極先行的優勢只使用了preg_replace。然而,我同意這裏的其他解決方案,它可能是最好的preg_match然後字符串連接。

$url = preg_replace('#^(?!https?://)#', 'http://', $url); 
0

如果您只是想讓您的RegEx匹配google.com e.a.,您所要做的就是製作www。可選的。請注意,這可能會引入其他問題,例如end.begin被識別爲URL。

/([^\w\/])((www\.)?[a-z0-9\-]+\.[a-z0-9\-]+)/i 
1

這是一個非正則表達式的黑客方式來做到這一點。

$url = 'google.com'; 
function addHTTP($url) { 
return 'http://'.str_replace('http://','',$url); 
}