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

前端 未结 4 1196
闹比i
闹比i 2020-12-29 17:56

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

相关标签:
4条回答
  • 2020-12-29 18:30

    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;
    }
    
    0 讨论(0)
  • 2020-12-29 18:30

    You are just using substr wrong.

    To get the last character you have just use negative offset: substr($path,-1)

    Your code lacks 2 fundamental things, essential for the programming:

    • debugging
    • documentation reading.

    Debugging is as simple as just echoing your variables.
    by echoing substr($path, 0, -1) you can make yourself aware that your code is somewhat wrong and by reading documentation you can see the right usage.

    0 讨论(0)
  • 2020-12-29 18:43

    you can try to use this function

        function endsWith($FullStr, $needle)
        {
            $StrLen = strlen($needle);
            $FullStrEnd = substr($FullStr, strlen($FullStr) - $StrLen);
            return $FullStrEnd == $needle;
        }
    

    taken from by blog post

    then use it like

    if (endsWith($path,'/') == false) 
    {
        $path = $path."/";
    }
    

    and offcourse if you do not want to use above function to siplify things then you should change the way you are using substr

    correct way to get last char is substr($path,-1)

    0 讨论(0)
  • 2020-12-29 18:47

    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 ./

    0 讨论(0)
提交回复
热议问题