www.webdeveloper.com
Results 1 to 5 of 5

Thread: Getting last part of URL

  1. #1
    Join Date
    May 2009
    Location
    Rochester, NY
    Posts
    364

    Question Getting last part of URL

    Ok, I'm stumped! I need to get the highest folder name in the URL, such as the examples below:

    www.fakesite.com/folder/this
    www.fakesite.com/folder/file/this/
    www.fakesite.com/this/index.html

    will all yield 'this'.

    How do I approach this using PHP or JavaScript?

    Thanks,
    M

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,327
    This seems to work, at least for those 3 test cases:
    PHP Code:
    <?php
    $test 
    = array(
       
    'www.fakesite.com/folder/this',
       
    'www.fakesite.com/folder/file/this/',
       
    'www.fakesite.com/this/index.html'
    );
    foreach(
    $test as $string) {
       if(
    preg_match('#/([^./]+)(/(.+\..+)?)?$#'$string$matches)) {
          echo 
    "<p>".$matches[1]."</p>\n";
       }
    }
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    May 2009
    Location
    Rochester, NY
    Posts
    364
    Well... thanks! That was very thorough. That did what I needed it to do. I don't think there's a rule or a 'best practice' in this case. Thanks for the solution!

  4. #4
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,327
    Glad it helped. I have to admit upon looking at it again, the regexp sure looks arcane, or else like random typing with the shift key held down.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  5. #5
    Join Date
    May 2009
    Location
    Rochester, NY
    Posts
    364
    I know! And I thought PHP had enough arbitrary punctuations before I saw this! Thanks again, though. It works well from what I tested.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles