www.webdeveloper.com
Results 1 to 4 of 4

Thread: preg_replace() urls

  1. #1
    Join Date
    Feb 2011
    Posts
    38

    Cool preg_replace() urls

    Hi guys,

    I have a complete link to an image which is dynamic so declared as a variable...

    eg url = 'http://somelink.com/images/image.jpg'

    I want to remove the url part with the exception of the image name and extention. So I'm looking to do something like this....

    change url from 'http://somelink.com/image.jpg' to just image.jpg.

    I've tried using preg_replace...

    This works...
    PHP Code:
    $url 'http://somelink.com/images/image.jpg';
    preg_replace('/http:\/\/somelink.com\/images\//'''$url); 
    This doesn't...
    PHP Code:
    $link 'http://somelink.com';
    $url 'http://somelink.com/images/image.jpg';
    preg_replace('/'.$link.'\/images\//'''$url); 
    I'm guessing I need to do something to $link to escape the slashes but I don't have a clue what to do! Can anyone help please?

    Thanks in advance

    Smithster
    Last edited by smithster; 02-18-2012 at 06:43 PM.

  2. #2
    Join Date
    Dec 2005
    Posts
    2,984
    explode is the easiest to use.

    PHP Code:
    $url 'http://example.com/path/to/someimage.jpg';

    $filename end(explode('/',$url)); 
    I've switched careers...
    I'm NO LONGER a scientist,
    but now a web developer...
    awesome.

  3. #3
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,245
    A couple options:
    PHP Code:
    $url 'http://example.com/path/to/someimage.jpg';
    $fileName basename($url);
    echo 
    $fileName
    A bit more robust:
    PHP Code:
    $url 'http://example.com/path/to/someimage.jpg?foo=bar#fubar';
    $fileName basename(parse_url($urlPHP_URL_PATH));
    echo 
    $fileName
    "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

  4. #4
    Join Date
    Feb 2011
    Posts
    38
    Quote Originally Posted by aj_nsc View Post
    explode is the easiest to use.

    PHP Code:
    $url 'http://example.com/path/to/someimage.jpg';

    $filename end(explode('/',$url)); 
    I use explode a lot but I never knew you could do that!! Thank you this worked a treat!

    @NogDog....

    Thank you for your suggestion, I've used the explode function as it works nicely for me and there will never be any parameters to consider in the url.

    Thanks guys

Thread Information

Users Browsing this Thread

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

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