PHP regular expression matches all urls

I need help creating a Regex that will match all URLs, for example, don't close the question as a duplicate, as I was looking for what I needed for a long time, and none of the answers I saw gave an answer, which solves my problem.

website.com

www.website.com

http://www.website.com

http://website.com

https://www.website.com

https://website.com

as well as something addictive

www.website.com/path-to-something

I am coding for something that shortens any url, but for that, first I need to match them all.

thanks

+6
source share
4 answers

This matches all your posts correctly:

preg_match_all('#[ -a-zA-Z0-9@ :%_\+.~\#?&//=]{2,256}\.[az]{2,4}\b(\/[ -a-zA-Z0-9@ :%_\+.~\#?&//=]*)?#si', $targetString, $result); 
+14
source

You want to use something like this:

 $string = 'www.blah.com'; $temp_string = (!preg_match('#^(ht|f)tps?://#', $string)) // check if protocol not present ? 'http://' . $string // temporarily add one : $string; // use current if (filter_var($temp_string, FILTER_VALIDATE_URL)) { echo 'is valid'; } else { echo 'not valid'; } 

This uses a PHP build to validate URLs. First, it will be checked whether the protocol is present, if it will not temporarily add it to the string being checked, and then run it by checking. This is accurate, unlike the current answer.

+4
source

You can use the following trick:

 $url = "your URL" $validation = "/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i"; if((bool)preg_match($validation, $url) === false) echo 'Not a valid URL'; 

I think this might work for you.

+2
source

Do not use regex. There is a PHP function to do what you want.

http://php.net/manual/en/function.parse-url.php

+1
source

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


All Articles