2012-01-12 33 views
1

我有一個表單,用戶可以在其中輸入一個URL。現在很明顯他們會放入www.example.com/path或example.com/path或http://www.example.com/path甚至http://example.com/pathURL解析到數據庫中

我想要做的是提取整個URL主機和路徑等..並把它放在一個標準的形式到我的數據庫。因此,無論輸入格式如何,它們在數據庫中都具有相同的格式。

所以輸入到輸出像下面

www.example.com/path -> http://www.example.com/path 
example.com/path -> http://www.example.com/path 
http://www.example.com/path -> http://www.example.com/path 
http://example.com/path ->http://www.example.com/path 

回答

2

的使用正則表達式的網址,然後使用驗證,並指定PREG_OFFSET_CAPTURE使它成爲在比賽中的值的數組時preg_match。然後將其操作爲滿足您的格式的字符串。

+0

很抱歉,但我真的很業餘在PHP所以不知道如何做任何的那 – rmaspero 2012-01-12 11:10:02

+0

使用正則表達式意味着你砍了一個碼成小塊分類以便於你可以修改或獲取每件作品的價值。例如,一個數字由數字組成,一個數字由數字0至9組成。 函數valid_number( \t $ digit =「(0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ) 「; \t如果(的preg_match(」 $位數*「){ \t \t回1; \t} \t返回0; } 符號 '|' 分隔的數字和符號」選項*'表示可以有零個或多個。 這些值將被放入數組中,以便您可以按照自己的方式操作它們。 TTP://php.net/manual/en/function.preg-match.php – 2012-01-12 11:30:13

1

查找下面的例子:

function updateUrl($url) { 
    if (strpos($url, '://')=== false && strpos($url, 'www.')=== false) { 
     $url = 'http://www.' . $url; 
    } 
    else if(strpos($url, '://')=== false) { 
     $url = 'http://' . $url; 
    } 
    else if(strpos($url, 'www.')=== false) { 
     $url = str_replace('http://','http://www.',$url); 
    } 
    else { 
     $url = $url; 
    } 
    return $url; 
} 
$url = "http://example.com/path"; 
echo updateUrl($url);