Tom
Tom

Reputation: 12998

PHP validate string to ensure it does not contain http:// or https:// or www

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

How can I adapt this to check for the above?

Upvotes: 0

Views: 1158

Answers (2)

Ahmed Ziani
Ahmed Ziani

Reputation: 1226

Try with this:

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

Upvotes: 1

chris85
chris85

Reputation: 23880

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

Upvotes: 2

Related Questions