0

If I have the following PATH as a string:

dirname/user folder/sample_file.png

How would I add the string _trash after the dirname/user folder in the PATH, so its result is:

dirname/user folder_trash/sample_file.png

2 Answers 2

2

This should work for you:

<?php

    $path = "dirname/user folder/sample_file.png";

    echo $path = dirname($path) . "_trash/" . basename($path);

?>

Output:

dirname/user folder_trash/sample_file.png

EDIT:

You can search for the folder and then just replace it with the new one:

<?php

    $path = "dirname/user folder/another folder/sample_file.png";  

    $searchFolder = "/user folder/";
    $replaceFolder = "user folder_trash";

    echo $path = preg_replace($searchFolder, $replaceFolder, $path, 1); 

?>

Output:

dirname/user folder_trash/another folder/sample_file.png

EDIT 2:

IF the sting follows the same pattern every time this should work to change the second folder:

<?php

    $path = "dirname/user folder/another folder/another folder/sample_file.png";  

    $parts = explode("/", $path);
    $parts[1] = $parts[1] . "_trash";

    echo $path = implode("/", $parts);

?>

Output:

dirname/user folder_trash/another folder/another folder/sample_file.png
Sign up to request clarification or add additional context in comments.

6 Comments

i already did that earlier. but if the path is dirname/user folder/another folder/sample_file.png or dirname/user folder/another folder/another folder/sample_file.png
Well u should have put that as a requirement in your question. So in short it's always the second folder that needs to be concatenated with _trash?
@StoledInk Updated my answer so now you can search for a folder and it gets replace with the new one
thats what i need sir DarkBee .
sir Rizier123 the user user folder is sample folder name only because there's a specific folder name for each user so i couldn't use the $searchFolder = "/user folder/";
|
0

Another way:

  1. You also use explode function to split string to items (using count function to get number of item).

  2. Then modify each item. It up to you.

  3. Finally, merge items to string by string concatenation

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.