php检查最后一个字符是否是“/”如果不是,则将其附加到

php
2022-08-30 10:00:08

我有这2段代码,我一直在玩,但似乎无法理解逻辑来坚持其中任何一个。

我试图看看一个给定的字符串是否在末尾有一个“/”,如果没有,那就添加它。

$path = '.';

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

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

我的问题是,如果我使等于,那么我得到这个作为输出$path'././/

这是我遇到问题的片段

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;

答案 1

你可能想得太多了。虽然该方法可以完美地工作,但使用rtrim()删除任何尾部斜杠然后添加一个斜杠可能会更简单。substr()

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

警告:这将修剪多个尾部正斜杠。所以成为.//////./


答案 2

我的解决方案:简单甚至转换反斜杠,对Windows开发人员有用:

function fixpath($p) {
    $p=str_replace('\\','/',trim($p));
    return (substr($p,-1)!='/') ? $p.='/' : $p;
}

推荐