php检查最后一个字符是否为'/',如果不是,则添加该字符 [英] php checking if the last character is a '/' if not then tack it on

查看:134
本文介绍了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 .= '/';

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

我遇到的问题是,如果我使$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;

推荐答案

您可能想得太多.虽然substr()方法可以完美地工作,但使用 rtrim() 可能会更简单,以删除所有尾随的斜杠,然后加一个.

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

这篇关于php检查最后一个字符是否为'/',如果不是,则添加该字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆