0

I am fetching Folder Path with the help of values stored in database, I am getting exact path name with $file_info[path] but this is getting output with / at end of every folder.

This above code is showing path like :

/folders/New Files/Latest/

And I want result like

/folders/New Files/Latest

Guys Please tell me exact solution for this query.

chris85
  • 23,846
  • 7
  • 34
  • 51
Kailash
  • 13
  • 1
  • 7

3 Answers3

1

It would probably be best to correct your variable so it doesn't append the last /.

In the meantime though I'd use rtrim.

echo rtrim('/folders/New Files/Latest/', '/');

Output:

/folders/New Files/Latest

Demo: https://eval.in/463160

This way you can be sure you are only removing a /s from the end of the string. (Note if /// were the ending and you only want one to be removed this wouldn't do that, this will remove all trailing /s).

chris85
  • 23,846
  • 7
  • 34
  • 51
  • Thank you so much @chris85 ! With echo it showing perfect result; but when I tried it with my code It's not working... – Kailash Nov 04 '15 at 18:02
  • `$folder = "rtrim(''.$file_info[path].'', '/')" ` here is what I trying – Kailash Nov 04 '15 at 18:02
  • Take off the quotes. `$folder = rtrim($file_info['path'], '/');`. Also `path` should be in quotes if it is a string. – chris85 Nov 04 '15 at 18:05
  • I tried as per you said but still not working on my code , I am adding code here please check out `$folder = rtrim($file_info['path'], '/'); $down = "$folder/$to";` this is what I need in my old script it was like `$folder = "/folder"; $down = "$folder/$to";` Then It works perfect ! CAn you please tell me where I am doing mistakes ? – Kailash Nov 04 '15 at 18:27
  • I'm not sure I'm following you. Is this an accurate example of what you are encountering? https://eval.in/463194 – chris85 Nov 04 '15 at 18:33
  • @KailashGhodke figured it out? – chris85 Nov 04 '15 at 18:58
  • Thank you so much ! I got it :) – Kailash Nov 05 '15 at 04:33
0

You can verify the last position of a / in the path:

if (strrpos($path, '/')==strlen($path)-1){
    // remove last character
    $path = substr($path,0,strlen($path)-1);
}
bdanos
  • 141
  • 9
  • *If length is given and is negative, then that many characters will be omitted from the end of string*. You do not need to call `strlen()`, can just set length to `-1` to remove last character. – Twisty Nov 04 '15 at 17:58
  • Thanks for this optimisation. – bdanos Nov 04 '15 at 21:11
0

You can use substr() for this.

substr($file_info[path], 0, -1);

If the value is '/folders/New Files/Latest/', it will now be '/folders/New Files/Latest'.

Twisty
  • 30,304
  • 2
  • 26
  • 45