View Full Version : Rewrite a url in a string http://www. ???

05-11-2008, 11:59 PM

I have a string that will contain a URL, this url will eventually be processed and needs to be in the format:


how would i check if it is written differently and rewrite it to that format if it is different...

for example someone enters http://www.google.com/ the script does nothing.

someone enters www.google.com/ the script adds http://

someone enters http://google.com/ the script adds www.

someone enters google.com/ the script adds http://www.

is there any premade/easy ways to do this, or if you have a function that you have made that would be great...

05-12-2008, 01:15 AM
You should research the power of regular expressions. http://us2.php.net/manual/en/ref.pcre.php

That in combination with a few clever if/else or case statements should do the job.

I <3 Lamp
05-12-2008, 04:45 PM

function url_checker($url)
if (substr($url,0,11) == "http://www.")
return $url;
if (substr($url,0,7) == "http://")
return "http://www." . substr($url,7,strlen($url) - 7);
return "http://www." . $url;


05-12-2008, 09:08 PM
No need for the strlen() call, the remainder of the string is assumed if the third parameter is omitted:

function format_url( $url )
while ( strtolower( substr( $url, 0, 7 ) ) == 'http://' )
$url = substr( $url, 7 );
while ( strtolower( substr( $url, 0, 4 ) ) == 'www.' )
$url = substr( $url, 4 );
return 'http://www.' . $url;

Or using a single RegExp:

function format_url( $url )
return 'http://www.' . preg_replace( '/^(\w+\:\/\/)*(www\.)*/i', '', $url );

...note that this will replace any protocol, ie: http://, ftp://, foo://, etc...