使用preg_replace在dirname和slash之后添加一个字符串

时间:2015-01-03 10:47:55

标签: php

如果我将以下PATH作为string

dirname/user folder/sample_file.png

如何在PATH中的_trash文件夹之后添加字符串dirname/user,结果如下:

dirname/user folder_trash/sample_file.png

2 个答案:

答案 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)

另一种方式:

  1. 您还可以使用explode函数将字符串拆分为项目(使用 count函数获取项目数。)

  2. 然后修改每个项目。由你决定。

  3. 最后,通过string concatenation

  4. 将项目合并到字符串中