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?

Tom
  • 12,776
  • 48
  • 145
  • 240
  • Please check link:- http://stackoverflow.com/questions/6427530/regular-expression-pattern-to-match-url-with-or-without-http-www – Alive to die - Anant Apr 14 '15 at 10:59
  • There are multiple TLDs and could be numerous directories. Do you only care about any named domain on `.com`? – chris85 Apr 14 '15 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. – Tom Apr 14 '15 at 11:10
  • Okay than how about. `#(^https?://|\w+\.com$)#` – chris85 Apr 14 '15 at 11:11
  • Not quite... the TLD is not important... just the http / https / www part - none of which should be present... – Tom Apr 14 '15 at 11:13
  • Oh, so no www is valid. Okay how about `#(^(https?://|www\.)`? – chris85 Apr 14 '15 at 11:15
  • Awesome @chris85 - looks like that's done the trick... add it as an answer and I'll give it the tick... – Tom Apr 14 '15 at 11:22

2 Answers2

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
mikeybeck
  • 582
  • 2
  • 15
  • 27
chris85
  • 23,846
  • 7
  • 34
  • 51
1

Try with this:

preg_match('#^((https?://)|www\.?)#i', $url) === 1
Ahmed Ziani
  • 1,206
  • 3
  • 14
  • 26