0

Note: I'm using an older PHP version so FILTER_VALIDATE_URL is not available at this time.

After many many searches I am still unable to find the exact answer that can cover all URL structure possibilities but at the end I'm gonna use this way:

I'm using the following function

1) Function to get proper scheme

function convertUrl ($url){
    $pattern = '#^http[s]?://#i';
    if(preg_match($pattern, $url) == 1) { // this url has proper scheme
        return $url;
    } else {
        return 'http://' . $url;
    }
}

2) Conditional to check if it is a URL or not

if (preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $url)) {
  echo "URL is valid";
}else {
  echo "URL is invalid<br>";
}

Guess What!? It works so perfect for all of these possibilities:

$url = "google.com";
$url = "www.google.com";
$url = "http://google.com";
$url = "http://www.google.com";
$url = "https://google.com";
$url = "https://www.codgoogleekarate.com";
$url = "subdomain.google.com";
$url = "https://subdomain.google.com";

But still have this edge case

$url = "blahblahblahblah";

The function convertUrl($url) will convert this to $url = "http://blahblahblahblah"; then the regex will consider it as valid URL while it isn't!!

How can I edit it so that it won't pass a URL with this structure http://blahblahblahblah

2 Answers 2

1

If you want to validate internet url's, add a check for including a dot (.) character in your reg-ex.

Note: http://blahblahblah is a valid url as is http://localhost

Sign up to request clarification or add additional context in comments.

1 Comment

Yes http://localhost is valid but since my website is online so why i do allow for http://localhost .. thanks for your answer and i do really need to edit the regex so it can check if there is . or not.
0

Try this:

if (preg_match("/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/", $url)) {
  echo "URL is valid";
}else {
  echo "URL is invalid<br>";
}

3 Comments

This is baloney. I can get the same results with /\./. It doesn't mean the url is valid.
@pguardiario test it with convertUrl function i've mention in my question, i've tested in almost all possibilities and it did the work perfect.
Right, but a stopped clock is also right sometimes. The fact that you're unable to tell the difference doesn't make this a correct answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.