Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php checking if the last character is a '/' if not then tack it on

Tags:

php

I have these 2 snippets of code that I have been playing with, but can't seem to get the logic to stick in either of them.

I am trying to see if a given string has a '/' at the end, if not then add it.

$path = '.';

if (substr($path, 0, -1) != '/')     $path .= '/'; 

and

if (strrpos('/', $path) !== true)     $path .= '/'; 

the issue im having is that if i make $path equal to './ then I get this as the output .//

this is the snippet of where i am having the issue

if (!is_array($paths))     $this->classPath[] = $paths; else     $this->classPath = $paths;  foreach ($this->classPath as $path) {      if (strrpos('/', $path) !== true)// || substr_count($path, '/') >= 0)         $path = $path . '/';     //else         //$this->classPath[] = $path;         //echo '0';     $pathArr[] = $path; 
like image 514
Eli Avatar asked Feb 18 '12 07:02

Eli


People also ask

How do I get the last character of a string in PHP?

Using substr() Method: The substr() is a built-in function in PHP that is used to extract a part of string. Example: For example, if the string is “Akshit loves GeeksForGeeks”. The last character of the string is “s”.

How can I get the last word in a sentence in PHP?

After getting the position of last occurring space we can easily get the last word in the string using the substr() function and store this in a new string variable. At last, we can use the strlen() function to find the length of the last word in the string.


2 Answers

You might be overthinking it. While the substr() method will work perfectly it might be simpler to use rtrim() to remove any trailing slashes and then add one on.

$path = rtrim($path, '/') . '/'; 

Caution: this will trim multiple trailing forward slashes. so .////// becomes ./

like image 64
Mike B Avatar answered Sep 25 '22 00:09

Mike B


My solution: simple and even converts back slashes, useful for windows developers:

function fixpath($p) {     $p=str_replace('\\','/',trim($p));     return (substr($p,-1)!='/') ? $p.='/' : $p; } 
like image 36
countach Avatar answered Sep 23 '22 00:09

countach