Brandon
Brandon

Reputation: 21

Prepend "http://" to URLs starting with or without "www." in a string

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

Answers (7)

jpwdesigns
jpwdesigns

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

user2428118
user2428118

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

Andrew Curioso
Andrew Curioso

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

RDL
RDL

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

Knobik
Knobik

Reputation: 383

$url = 'http://' . $url;

the simpliest way possible :o

Upvotes: 0

vicTROLLA
vicTROLLA

Reputation: 1529

There are better ways to do this, but this will work:

if(!preg_match("#^http:\/\/#", $url)) {
         $url = "http://".$url;
}

Upvotes: 0

The Mask
The Mask

Reputation: 17477

$url = "www.google.com";
if(!preg_match("/^https/i",$url))
    $url = "http://$url"; 

Upvotes: 0

Related Questions