2012-01-12 30 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);