Tutorial :Check if directory path ends with DIRECTORY_SEPARATOR


In PHP I'm receiving a string from the user for a local file directory $path

I want to know if they've included the trailing slash (/) or not. I would like this to be cross platform so I'd like to use the PHP constant DIRECTORY_SEPARATOR

My failed attempts include trying to do a preg_match like

preg_match("/" . DIRECTORY_SEPARATOR . "$/", $path);  

I basically just want an elegant way to test if the string ends with the DIRECTORY_SEPARATOR.


To fix your regexp:

preg_match("/" . preg_quote(DIRECTORY_SEPARATOR) . "$/", $path);  

But there may be simpler ways to achieve your goal:



what's wrong with a simple substr($path,-1)==DIRECTORY_SEPARATOR ?


A trival way of working this out would be to use...

$sepPresent = $path{strlen($path) - 1} == DIRECTORY_SEPARATOR ? true : false;  

...which would be a lot more efficient than a regular expression. Then again, this will fail if DIRECTORY_SEPARATOR isn't a single character.


Could also use array access notation

$endsInDS = $str[strlen($str)-1] === DIRECTORY_SEPARATOR;  


I think depending on platform you can end up with an invalid regular expression on the first argument.

Your solution is elegant per design. Nice coding. But remember that directory separators usually are special characters. It may needs some escaping.

EDIT #1 I liked the proposed solution

$sepPresent = $path{strlen($path) - 1} == DIRECTORY_SEPARATOR ? true : false;  

And to work it out I suggest:

$sepPresent = $path{strlen($path) - strlen(DIRECTORY_SEPARATOR)} === DIRECTORY_SEPARATOR ? true : false;  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »