PHP Regex that only matches valid, valid URLs

I am looking for a regex that matches valid, online addresses.

For instance:

exmaple.com
http://exmaple.com
https://exmaple.com
www.exmaple.com
http://www.example.com
https://www.example.com

And special domains and extensions, such as:

t.co
example.deals
sh.party

And so on, but will not meet all the complex things like ftp, getquery or URL-address type 2.3.3.1.

I used '#(www\.|https?://)?[a-z0-9]+\.[a-z0-9]{2,4}\S*#i', but it detects dates , for example 3.3.2017.

I need this because I apply get_headersto every URL found, and when I do get_headersfor invalid URLs such as date, I get:

get_headers(http://03.03.2017): failed to open stream: Connection timed out

TL DR: I am looking for a regex that matches only URLs that you can apply get_headers()on.

Thanks for the help!

+4
2

, Regex - URL. FILTER_VALIDATE_URL:

<?php
 $url = "https://www.w3schools.com";

 if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
   echo("$url is a valid URL");
 } else {
   echo("$url is not a valid URL");
 }
 ?>
+2
#(https?:\/\/)?([a-z0-9_~-]+\.)+[a-z]{2,5}(\/\S*)?#i

EDIT: : http https . , 2-5 .

+1

Source: https://habr.com/ru/post/1671389/


All Articles