Reputation: 12998
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
Reputation: 1226
Try with this:
preg_match('#^((https?://)|www\.?)#i', $url) === 1
Upvotes: 1
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