Reputation: 4087
How can I add http://www
to url in an elegant way? I could do a few if statements, but I prefer something neat.
The idea is to create a function addHttpWWW that returns the following, for the inputs below:
google.com => http://www.google.com
http://www.google.com => http://www.google.com
www.google.com => http://www.google.com
http://google.com => http://www.google.com
Upvotes: 0
Views: 261
Reputation: 13
if u use jquery in your page : here is a solution to after ajax works you can have this: remmeber its work for 1.7.2 version ;)
<input type="text" id="txt_url" />
//...............................................
$("body").on("keyup","#txt_url",function() {
var el=document.getElementById('txt_url');
el.onkeyup=function();
var str=el.value;
if(str=='') return;
if(str.indexOf('http://')==-1 && str.length >= 7)
el.value='http://'+str;
}
});
Working solution:
Upvotes: -3
Reputation: 14678
$input = "google.com"; //Or whatever you want.
$output = "http://www." + str_replace(array("http://www.", "http://", "www."), "", $input);
Upvotes: 3
Reputation: 2315
$url = preg_replace('#(?:http(s)?://)?(?:www\.)?(.+)#', 'http\1://www.\2', $url);
Upvotes: 11