gpt4 book ai didi

php 检查最后一个字符是否为 '/' 如果不是则将其添加

转载 作者:IT王子 更新时间:2023-10-29 00:53:53 24 4
gpt4 key购买 nike

我有这 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;

最佳答案

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

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

注意:这将修剪多个尾部正斜杠。所以 .////// 变成 ./

关于php 检查最后一个字符是否为 '/' 如果不是则将其添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9339619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com