1

I've got a URL as a string, for example:

http://example.com/sub/sub2/hello/

I'd like to add another subfolder to it with PHP, before hello, so it should look like this:

http://example.com/sub/sub2/sub3/hello/

I thought about using explode to separate the URL by slashes, and adding another one before the last one, but I'm pretty sure I over complicate it. Is there an easier way?

5
  • 1
    Am I the only one how don't see any differences between both strings? Commented Apr 1, 2015 at 11:35
  • @Rizier123 I am too with you. :) Commented Apr 1, 2015 at 11:37
  • oh, sorry guys, updated my question :) Commented Apr 1, 2015 at 11:38
  • So now it's the question where and how do you want to define where you include the sub folder? (I mean is it always before the last folder where you want to add a folder or is it every time after the second folder where you want to add another one?) Commented Apr 1, 2015 at 11:39
  • 1
    I want to add a third subfolder before the last folder (the last folder is hello) in the easiest way possible. Sorry if it wasn't clear. Commented Apr 1, 2015 at 11:42

3 Answers 3

1

This should work for you:

(Here I just put the extra folder between the basename() and the dirname() of the string so that it is right before the last part of your url)

<?php

    $str = "http://example.com/sub/sub2/hello/";
    $folder = "sub3";

    echo dirname($str) . "/$folder/" . basename($str);

?>

output:

http://example.com/sub/sub2/sub3/hello
Sign up to request clarification or add additional context in comments.

Comments

1

If your url has this specific format you can use this:

$main_url = 'http://example.com/sub/sub2/';
$end_url_part = 'hello/';
$subfolder = 'sub3/';

if (isset($subfolder)) {
    return $main_url.$subfolder.$end_url_part;
} else {
   return $main_url.$end_url_part;
}

Comments

1

explode, splice, implode:

$str = "http://example.com/sub/sub2/hello/";
$str_arr = explode('/', $str);
array_splice($str_arr, -2, 0, 'sub3');
$str_new = implode('/', $str_arr);
// http://example.com/sub/sub2/sub3/hello/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.