PHP url validation + detection

二次信任 提交于 2019-12-10 12:13:57

问题


So here is what I need to do.

If an user enters this: http://site.com I need to remove http:// so the string will be site.com , if an user enters http://www.site.com I need to remove http://www. or if the user enters www.site.com I need to remove www. or he can also enter site.com it will be good as well.

I have a function here, but doesn't work how I want to, and I suck at regex.

preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $_POST['link'])

回答1:


I don't think I'd use regex for this, since you're only really checking for what is at the beginning of the string. So:

$link = $_POST['link'];
if (stripos($link, 'http://') === 0)
{
    $link = substr($link, 7);
}
elseif (stripos($link, 'https://') === 0)
{
    $link = substr($link, 8);
}
if (stripos($link, 'www.') === 0)
{
    $link = substr($link, 4);
}

should take care of it.




回答2:


Use filter_var() instead.

if (filter_var($_POST['link'], FILTER_VALIDATE_URL)) {
    // valid URL
} else {
   // not valid
}



回答3:


There is also parse_url function.




回答4:


i always go with str_replace haha

str_replace('http://','',str_replace('www.','',$url))



回答5:


I think what you're looking for is a multi-stage preg_replace():

$tmp = strtolower($_POST['link']) ;
$tmp = preg_replace('/^http(s)?/', '', $tmp);
$domain = preg_replace('/^www./', '', $tmp) ;

This simplifies the required regex quite a bit too.



来源:https://stackoverflow.com/questions/3826633/php-url-validation-detection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!