Reputation: 21
I need help replacing a link like google.com
into http://www.example.com
$url = preg_replace("/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1http://$2", $url);
$output = htmlspecialchars(urldecode($url));
I'm using an <iframe>
like:
<iframe src='$url'></iframe>
However, if its src="example.com"
instead of http://example.com
it will not work. So, how can I transform example.com
into http://www.example.com
?
Upvotes: 2
Views: 420
Reputation: 21
Here's a non regex hack way to do it.
$url = 'google.com';
function addHTTP($url) {
return 'http://'.str_replace('http://','',$url);
}
Upvotes: 1
Reputation: 8114
If you just want to make your RegEx match google.com e.a., all you have to do is make www. optional. Please note that this may introduce other problems, such as end.begin
being recognized as an URL.
/([^\w\/])((www\.)?[a-z0-9\-]+\.[a-z0-9\-]+)/i
Upvotes: 0
Reputation: 2191
Just for fun, here's one that uses just preg_replace by taking advantage of a negative lookahead. However, I agree with the other solutions here, that it is probably best to just to a preg_match and then a string concatenation.
$url = preg_replace('#^(?!https?://)#', 'http://', $url);
Upvotes: 0
Reputation: 7961
How about checking if http://
is on the beginning of it and if not tag it on? Like so:
$url = 'google.com';
if (!preg_match('#^http://#', $url)) {
$url = 'http://'.$url;
}
Upvotes: 0
Reputation: 1529
There are better ways to do this, but this will work:
if(!preg_match("#^http:\/\/#", $url)) {
$url = "http://".$url;
}
Upvotes: 0
Reputation: 17477
$url = "www.google.com";
if(!preg_match("/^https/i",$url))
$url = "http://$url";
Upvotes: 0