Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder the-dream's Avatar
    Join Date
    Mar 2007
    Location
    Northamptonshire, UK
    Posts
    477
    Thanks
    8
    Thanked 4 Times in 4 Posts

    Rewrite a url in a string http://www. ???

    Hi,

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

    http://www.

    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...

  • #2
    Regular Coder
    Join Date
    May 2008
    Location
    Ohio
    Posts
    231
    Thanks
    3
    Thanked 21 Times in 21 Posts
    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.

  • #3
    New Coder
    Join Date
    May 2008
    Posts
    50
    Thanks
    0
    Thanked 0 Times in 0 Posts
    PHP Code:

    <?php

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

    ?>

  • #4
    Senior Coder kbluhm's Avatar
    Join Date
    Apr 2007
    Location
    Philadelphia, PA, USA
    Posts
    1,509
    Thanks
    3
    Thanked 258 Times in 254 Posts
    No need for the strlen() call, the remainder of the string is assumed if the third parameter is omitted:
    PHP Code:
    function format_url$url )
    {
        while ( 
    strtolowersubstr$url0) ) == 'http://' )
        {
            
    $url substr$url);
        }
        while ( 
    strtolowersubstr$url0) ) == 'www.' )
        {
            
    $url substr$url);
        }
        return 
    'http://www.' $url;

    Or using a single RegExp:
    PHP Code:
    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...
    Last edited by kbluhm; 05-13-2008 at 11:09 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •