Search code examples
phpurlurlparse

How to insert an additional path into URL using PHP?


Let say I've this URL:

http://example.com/image-title/987654/

I want to insert "download" to the part between "image-title" and "987654" so it would look like:

http://example.com/image-title/download/987654/

help would be greatly appreciated! thank you.


Solution

  • There are a number of ways to do this in PHP:

    • Split and reconstruct using explode(), array_merge, implode()
    • Using substring()
    • Using a regular expression
    • Using str_replace

    Assuming all the url's conform to the same structure (image-title/[image_id]) i recommend using str_replace like so:

    $url = str_replace('image-title', 'image-title/download', $url);
    

    If however image-title is dynamic (the actual title of the image) i recommend splitting and reconstructing like so:

    $urlParts = explode('/', $url);
    $urlParts = array_merge(array_slice($urlParts, 0, 3), (array)'download', array_slice($urlParts, 3));
    $url = implode('/', $urlParts);