Check if the directory path DIRECTORY_SEPARATOR ends

In PHP, I get a line from the user for the local $path file directory

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

My unsuccessful attempts include trying to execute preg_match, like

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

I just need an elegant way to check if a string ends with DIRECTORY_SEPARATOR .

+4
source share
5 answers

To fix your regular expression:

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

But there may be simpler ways to achieve your goal:

 rtrim($path,DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR; 
+16
source

what is wrong with simple substr($path,-1)==DIRECTORY_SEPARATOR ?

+1
source

A triangular way of working on this would be to use ...

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

... which would be much more efficient than regex. Again, this will happen if DIRECTORY_SEPARATOR is not a single character.

0
source

You can also use array access notation

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

I think that depending on the platform, you might get an invalid regular expression for the first argument.

Your solution is elegant in design. Good coding. But remember that directory separators are usually special characters. Some acceleration may be required.

EDIT # 1 I liked the proposed solution

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

And for its development, I suggest:

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

All Articles