Alex Borsody
Alex Borsody

Reputation: 2040

different kind of regex to match a url

each part of this regex works alone but when i string them together it does not match a url with http or www followed by one of the listed TLDs.

(preg_match('/http\:\/\/(www\.)?[a-z](\.com|\.org|\.net|\.mil|\.edu|\.COM|\.ORG|\.NET|\.MIL|\.EDU)$/', $bandUrl))

Upvotes: 0

Views: 260

Answers (4)

Denis de Bernardy
Denis de Bernardy

Reputation: 78413

Don't use a regex.

filter_var('http://www.example.com', FILTER_VALIDATE_URL);

Upvotes: 1

anubhava
anubhava

Reputation: 784918

For matching URL following code should work:

<?php
    $regex = "((https?|ftp)\:\/\/)?"; // SCHEME
    $regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
    $regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP
    $regex .= "(\:[0-9]{2,5})?"; // Port
    $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
    $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
    $regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor
?>

Then, the correct way to check against the regex ist as follows:

<?php
       if(preg_match("/^$regex$/", $url))
       {
               return true;
       }
?>

Courtesy: Comments made by splattermania on PHP manual: http://php.net/manual/en/function.preg-match.php

Upvotes: 0

cOle2
cOle2

Reputation: 4784

Your [a-z] will match only one character (ie www.a.com). You'd be better off making it something like [a-z0-9\-]+. Note the + means more than one.

Upvotes: 1

mario
mario

Reputation: 145482

You probably left out the + after [a-z] (which btw is not correct to match all valid URLs). And instead of listing both uppercase and lowercase .TLDs, you could use the /i flag:

preg_match('/http\:\/\/(www\.)?[a-z]+(\.com|\.org|\.net|\.mil|\.edu$/i',

Btw, as alternative you could use filter_var($url, FILTER_VALIDATE_URL) for testing.

Upvotes: 3

Related Questions