0

I have the following if statement to check whether or not a string begins with http:// or https:// but I also need it to check whether it begins with www.

if (preg_match('#^https?://#i', $url) === 1) {
    // Starts with http:// or https:// (case insensitive).
}

So the following would fail:

But the following would pass the validation

  • website.com

How can I adapt this to check for the above?

7
  • Please check link:- stackoverflow.com/questions/6427530/… Commented Apr 14, 2015 at 10:59
  • There are multiple TLDs and could be numerous directories. Do you only care about any named domain on .com? Commented Apr 14, 2015 at 11:03
  • @chris85 - Ultimately I want to make sure that 'myurl.com' is also valid but wanted to work this out as a start point. Commented Apr 14, 2015 at 11:10
  • Okay than how about. #(^https?://|\w+\.com$)# Commented Apr 14, 2015 at 11:11
  • Not quite... the TLD is not important... just the http / https / www part - none of which should be present... Commented Apr 14, 2015 at 11:13

2 Answers 2

2

Here's the regex #^(https?://|www\.)#i, and here's a way to test for future URLs (command line, change \n to <br> if testing in a browser). 

<?php
$urls = array('http://www.website.com', 'https://www.website.com', 'http://website.com', 'https://website.com', 'www.website.com', 'website.com');
foreach($urls as $url) {
    if (preg_match('#^(https?://|www\.)#i', $url) === 1){
        echo $url . ' matches' . "\n";
    } else {
        echo $url . ' fails' . "\n";
    }
}

Output:

http://www.website.com matches
https://www.website.com matches
http://website.com matches
https://website.com matches
www.website.com matches
website.com fails
Sign up to request clarification or add additional context in comments.

Comments

1

Try with this:

preg_match('#^((https?://)|www\.?)#i', $url) === 1

3 Comments

Targeted string doesn't have www and doesn't start with http.
Still not quite there... http://website.com and https://website.com would still pass
This fails because you've made both parameters optional.

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.