check if a string is a URL [duplicate]

2019-01-23 15:18发布

This question already has an answer here:

I've seen many questions but wasn't able to understand how it works as I want a more simple case.

If we have text, whatever it is, I'd like to check if it is a URL or not.

$text = "something.com"; //this is a url

if (!IsUrl($text)){
    echo "No it is not url";
    exit; // die well
}else{
    echo "Yes it is url";
    // my else codes goes
}

function IsUrl($url){
    // ???
}

Is there any other way rather than checking with JavaScript in the case JS is blocked?

标签: php regex url
8条回答
\"骚年 ilove
2楼-- · 2019-01-23 15:50

You could use the following regex pattern to check if your variable is an url or not :

$pattern = "\b(([\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/)))";
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-23 16:00

I don't think there is a definitive answer to this. Example of a valid URL:

localhost
http://xxx.xxx.xxx/alkjnsdf
abs.com

If you have some text. and not a large amount of it. You can check by doing a CURL request and see if that returns a valid response. Otherwise if I put localhost, it could be a link and it could be something else and you wouldn't be able check it.

查看更多
登录 后发表回答