如果我将以下PATH
作为string
:
dirname/user folder/sample_file.png
如何在PATH中的_trash
文件夹之后添加字符串dirname/user
,结果如下:
dirname/user folder_trash/sample_file.png
答案 0 :(得分:2)
这应该适合你:
<?php
$path = "dirname/user folder/sample_file.png";
echo $path = dirname($path) . "_trash/" . basename($path);
?>
输出:
dirname/user folder_trash/sample_file.png
修改强>
您可以搜索该文件夹,然后将其替换为新文件夹:
<?php
$path = "dirname/user folder/another folder/sample_file.png";
$searchFolder = "/user folder/";
$replaceFolder = "user folder_trash";
echo $path = preg_replace($searchFolder, $replaceFolder, $path, 1);
?>
输出:
dirname/user folder_trash/another folder/sample_file.png
编辑2:
如果每次更改第二个文件夹时,sting都遵循相同的模式:
<?php
$path = "dirname/user folder/another folder/another folder/sample_file.png";
$parts = explode("/", $path);
$parts[1] = $parts[1] . "_trash";
echo $path = implode("/", $parts);
?>
输出:
dirname/user folder_trash/another folder/another folder/sample_file.png
答案 1 :(得分:0)
另一种方式:
您还可以使用explode
函数将字符串拆分为项目(使用
count
函数获取项目数。)
然后修改每个项目。由你决定。
最后,通过string concatenation