Is regex a good way to test a url

2019-02-13 21:16发布

I'm trying to test the validity of a url entered with php5. I thought of using regex, but assuming that it works correctly all the time, it only solves the problem of the url being syntactically valid. It doesn't tell me anything about the url being correct or working.

I'm trying to find another solution to do both if possible. Or is it better to find 2 separate solutions for this?

If a regex is the way to go, what tested regexes exist for urls?

标签: php regex url
8条回答
放荡不羁爱自由
2楼-- · 2019-02-13 21:32

What I would do:

  1. Check that the URL is valid using a very open regex or filer_var with FILTER_VALIDATE_URL.
  2. Do an file_get_contents on the url and check that $http_response_header[0] contains a 200 HTTP resoponse.

Now, that's dirty, sure there is some more elegant version using curl and stuff.

查看更多
Anthone
3楼-- · 2019-02-13 21:33

RegExLib is good place to go for Reg Ex expressions

http://www.regexlib.com/Search.aspx?k=URL

查看更多
Rolldiameter
4楼-- · 2019-02-13 21:33

i would use regex to go about solving this problem and i hate regex. This tool however makes my life so much easier... check it out >> http://gskinner.com/RegExr/

查看更多
干净又极端
5楼-- · 2019-02-13 21:35

Instead of cracking my head over a regex (URLs are very complicated), I just use filter_var(), and then attempt to ping the URL using cURL:

if (filter_var($url, FILTER_VALIDATE_URL) !== false)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_NOBODY, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_exec($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($status_code >= 200 && $status_code < 400)
    {
        echo 'URL is valid!';
    }
}
查看更多
Evening l夕情丶
6楼-- · 2019-02-13 21:38

In order to test that a URL is 'correct or working', you'll need to actually try and interact with it (like a web browser would, for example).

I'd recommend an HTTP library for Perl like LWP::Simple to do so.

查看更多
太酷不给撩
7楼-- · 2019-02-13 21:40

Pinging a URL to see if it is a valid URL is nonsense!

  • What if host is down?
  • What if the domain is not ping-able?

If you really want to do a "live" testing, better try to resolve the URL by using DSN. DNS is more reliable then PING or HTTP.

<?php
$ip = gethostbyname('www.example.com');

echo $ip;
?>

But even if this fails URL can be valid. It just have no DNS entry. So it depends on your needs.

查看更多
登录 后发表回答