Skip to content
Advertisement

Detect the right name in string

So I was wondering how to detect the right files, by their names, when I scan through them.

Right now when I open a pop-up window, I GET a id (?id=2451961), and this id is used to detect image files in a folder. But how should i detect them?

Is there a way to say, the start of the files name to the first non-number should be the id, and if it’s equal to the id then thats one of the files?

The folder with some files could be this:

enter image description here

Right now I loop through the files like this, but it doesn’t get the file '2451961 - Copy.png':

JavaScript

Note: there is a statement exclude = .log files in the code, which is because there is some files containing text which shouldn’t be takes into consideration.

The files i want to get in this example is these:

enter image description here

NOTE: Not all images will be .png, there could be a .jpg or something like that.

file names:

JavaScript

Advertisement

Answer

Regex looks like a better/right tool for this job. Your regex could look like below:

JavaScript

preg_quote is just for escaping of any regex metacharacters. So, your file name should start with the ID followed by a non digit, which is D. We won’t have to care about file extensions if we do it this way.

Snippet:

JavaScript

Online Demo

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement