dtdr57046
2015-01-03 10:47
采纳率: 100%
浏览 60
已采纳

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

If I have the following PATH as a string:

dirname/user folder/sample_file.png

How would I add the string _trash after the dirname/user folder in the PATH, so its result is:

dirname/user folder_trash/sample_file.png

图片转代码服务由CSDN问答提供 功能建议

如果我有以下 PATH 作为字符串

  dirname / user folder / sample_file.png 
   
 
 

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

  dirname / user folder_trash / sample_file.png 
 <  / code>  
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dpbvpgvrhwxen3222 2015-01-03 10:50
    已采纳

    This should work for you:

    <?php
    
        $path = "dirname/user folder/sample_file.png";
    
        echo $path = dirname($path) . "_trash/" . basename($path);
    
    ?>
    

    Output:

    dirname/user folder_trash/sample_file.png
    

    EDIT:

    You can search for the folder and then just replace it with the new one:

    <?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); 
    
    ?>
    

    Output:

    dirname/user folder_trash/another folder/sample_file.png
    

    EDIT 2:

    IF the sting follows the same pattern every time this should work to change the second folder:

    <?php
    
        $path = "dirname/user folder/another folder/another folder/sample_file.png";  
    
        $parts = explode("/", $path);
        $parts[1] = $parts[1] . "_trash";
    
        echo $path = implode("/", $parts);
    
    ?>
    

    Output:

    dirname/user folder_trash/another folder/another folder/sample_file.png
    
    点赞 评论
  • dox19458 2015-01-03 11:15

    Another way:

    1. You also use explode function to split string to items (using count function to get number of item).

    2. Then modify each item. It up to you.

    3. Finally, merge items to string by string concatenation

    点赞 评论

相关推荐 更多相似问题