0

The directory I'm working in is

C:\xampp\htdocs\example\profile\john_doe

I want to know how I'd echo john_doe using this? I'm using PHP

J. Doe
  • 13
  • 2

2 Answers2

1

if you are trying to get the base directory name , you can simply do this :

<?php

  echo basename(__DIR__);

?>
azjezz
  • 3,827
  • 1
  • 14
  • 35
-1

Try basename function.

echo(basename('C:\xampp\htdocs\example\profile\john_doe'));

This should echo 'john_doe'.

sthames42
  • 888
  • 8
  • 19
  • Note that on environments other than Windows, this will not work correctly with backslashes. If you wanted to support backslashes on eg. Linux you could replace them with forward slashes. – Ali Gangji Mar 03 '18 at 17:45
  • From PHP online manual (http://php.net/manual/en/function.basename.php): "On Windows, both slash (/) and backslash (\) are used as directory separator character." Don't worry about the downvote. I've seen this before on SO. Some people just like to do it. I've used basename for this in a half-dozen languages and it's the obvious answer. BTW, the online PHP manual is pretty comprehensive. You can find good documentation there. – sthames42 Mar 03 '18 at 17:47
  • FYI, Ali Gangji is correct. basename will not work with Windows path on a Linux OS. But Linux will give you the working folder correctly with forward slashes so it hardly seems relevant. – sthames42 Mar 03 '18 at 17:55
  • I was just providing additional information. I did not downvote your answer. I was about to give the same one myself. – Ali Gangji Mar 03 '18 at 18:07
  • your answer got downvoted cause this answer isn't correct ! this would work in this situation but as soon as you change your project directory , it won't work ! this is not how you get the base-name of the current directory – azjezz Mar 03 '18 at 18:11
  • That's pretty arrogant, azjezz. The answer is not incorrect. He asked the question with a specific path and I answered it with the same path. I assumed he would know enough to use a variable or the current WD constant. I upvoted your answer because it provided more useful information. That did not negate that my answer was correct, however. Especially since it worked for him. If you had said you downvoted because you felt the answer was incomplete, it would still be rude and arrogant but it would have been a supportable argument. To say it was not correct? Not so much. – sthames42 Mar 03 '18 at 19:29