【问题标题】:php check if file exist: check only portionphp 检查文件是否存在:仅检查部分
【发布时间】:2023-04-04 04:53:01
【问题描述】:

在 php 中,我们可以使用检查文件是否存在

if(file_exists("destination/"))
{
    condition
}

但我想做的是……

例如,我的目的地已经有这个文件

hello_this_is_filename(2).doc

我如何知道该目录中是否存在名称包含字符的文件

hello_this_is_filename

我想这样搜索,因为...如果该目录上存在,我会做的是...将文件重命名为

hello_this_is_filename(3).doc

我还需要计算我的搜索是否存在,所以我知道我要输入什么数字

(3), (4), (5) and so on

有什么帮助吗?

【问题讨论】:

标签: php file-exists


【解决方案1】:

使用glob

if (count(glob("destination/hello_this_is_filename*.doc"))) {
  //...
}

【讨论】:

    【解决方案2】:

    利用 Marc B 的建议和 xdazz,我会做以下事情:

    <?php
    $files = glob("destination/hello_this_is_filename*");
    if (count($files)) {
       sort($files);
    
       // last one contains the name we need to get the number of
       preg_match("([\d+])", end($files), $matches);
    
       $value = 0;
       if (count($matches)) {
          // increment by one
          $value = $matches[0];
       }
    
       $newfilename = "destination/hello_this_is_filename (" . ++$value . ").doc";
    ?>
    

    抱歉,这是未经测试的,但认为它为其他人提供了正则表达式工作以实际执行递增...

    【讨论】:

      猜你喜欢
      • 2023-01-02
      • 2013-01-19
      • 2011-05-14
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      相关资源
      最近更新 更多