Sam San
Sam San

Reputation: 6903

php check if file exist: check only portion

in php we can check if file exist using

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

but what I wanted to do is...

for example I already have this file on my destination

hello_this_is_filename(2).doc

how would I know if there is a file in that directory having a name containing a character

hello_this_is_filename

I wanted to search that way because... if there is exists on that directory, what will I do is... renaming the file into

hello_this_is_filename(3).doc

I also need to count the existence of my search so I know what number I'm going to put like

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

any help?

Upvotes: 1

Views: 209

Answers (2)

endyourif
endyourif

Reputation: 2202

Leveraging Marc B's suggestion and xdazz, I would do something as follows:

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

Sorry this is untested, but thought it provides others with the regexp work to actually do the incrementing...

Upvotes: 0

xdazz
xdazz

Reputation: 160933

Use glob.

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

Upvotes: 5

Related Questions