PHP Find directory stating part of directory name

Asked

Viewed 62 times

2

Hello!

I already have a prototype application running in PHP, where I access photos from a given directory. However, the directories were not very friendly, for example:

2016/783/01/2016-07-26-00001

To get a little more friendly, it would be interesting that the third and fourth elements that are respectively category and event, could have a name on the right.

Thus remaining:

2016/783/01-relatorios/2016-07-26-00001-relatorio semanal 21

What I would like is to access this same folder but totally ignoring the texts of the path, where basically the code would ignore the texts.

I’ve never had to do this, I’m reading all about Filesystem and correlates, but I haven’t found a solution yet!

These folders are all linked with databases, in theory there is no need to do this inclusion of the texts on the way, however, I’m thinking of implementing this, because in a future I believe that someone who goes tampering with Backup will end up causing me problems because you are not understanding anything.

Thank you!

  • 2

    Would renaming the files be costly for you in this case? I would think about that possibility. The "magic" you want to do, I can imagine something like glob or FilterIterator combined with RegexIterator.

  • Hi Wallace! Actually, the system already names the files. People select 1 or more files and upload them. In this process, the uploaded file gets a specific name and goes to its specific directory. What I want is to inform only the numerical data that is in the database and these open the directory that contains text data. As I explained above, I’m just trying to avoid future problems. Because it’s already working round. I’m already searching with the blob and will see tb with Filteriteration. Thanks, hug!

  • The files are with this standard name: 2016-07-26-783-00001-DJI_0754.jpg, but the point is that they are separated by directories. We structure the directory tree as YEAR > WORK OF THE COMPANY > Category > Event, some works of the company last years, and each work has a number, etc. Complex!!! kkkkk

1 answer

0

That should do what you want:

<?php
$dir = "2016/783/01-relatorios/2016-07-26-00001-relatorio semanal 21";

$peaces = explode("/", $dir);

foreach ($peaces as $idx => $peace) {
    if (preg_match("/-\D+/", $peace, $match)) {
        $new_peace = substr($peace, 0, strpos($peace, $match[0]));
        $peaces[$idx] = $new_peace;
    }
}

$dir = implode("/", $peaces);
echo $dir;
?>

We are searching for a pattern by the (-) character followed by no digits.

The exit will be:

2016/783/01/2016-07-26-00001

Browser other questions tagged

You are not signed in. Login or sign up in order to post.