Help with regex on url

Discussion in 'Programming' started by jiggyjiggy, Apr 9, 2008.

  1. #1
    Does anyone know a good regex that will make these two changes to the same url?

    a) add a folder name to the url
    b) add .html at the end of the url

    I will prefer to do this on the html code rather than on the fly. So from:

    <a href="http://mydomain.com/url1">
    <a href="http://mydomain.com/url2">
    etc..

    To

    <a href="http://mydomain.com/folder/url1.html">
    <a href="http://mydomain.com/folder/url2.html">
    etc..

    Many thanks.
     
    jiggyjiggy, Apr 9, 2008 IP
  2. Louis11

    Louis11 Active Member

    Messages:
    783
    Likes Received:
    26
    Best Answers:
    0
    Trophy Points:
    70
    #2
    Meh, I don't think you need to use a regular expression for a string so short. Seems to me It would over complicate things just a tad. If I where you I would just explode the string be / and then put it back together with the folder in the correct place.

    Here check this out (it's rough but you get the idea):
    
    <?
        function addFolder($url, $folder){
    		$url = str_replace("http://", "", $url);
            $url = explode("/", $url);
    
            return "http://" . $url[0] . "/" . $folder . "/" . $url[1] . ".html";
        }
    ?>
    
    PHP:
    This of course takes for granted that the URL's will always be "url.com/url1". But the code can easily be modified to accommodate a different URL formatting.

    Cheers,
    Louis
     
    Louis11, Apr 9, 2008 IP
  3. mures

    mures Member

    Messages:
    7
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    36
    #3
    you can use a regex like this:

    
    $folder= "foldername";
    $url = "http://google.com/search";
    $new_url = preg_replace( "/^http:\/\/(.*?)\/(.*)$/" ,
                      "http://\$1$folder\$2.html",  $url);
    
    PHP:
    Hope that helps.

    Mures
     
    mures, Apr 9, 2008 IP