0

Is there any way i can search a files array to match a certain string?

So i have a directory with images inside and i put them in a variable like so

$images = scandir('directory goes here');

now i want to search that images array for images with a certain name. Like for example all images with a name starting with 'cars_hatchback'.

I've tried using the glob function but it seems i'm coming up short.

Is there any way to accomplish this? Thanks in advance!

1

3 Answers 3

2

Use preg_grep to search an array with a pattern:

$images = scandir('directory goes here');
$result = preg_grep ("/^cars_hatchback.*/", $images);

Source: http://php.net/manual/en/function.preg-grep.php

Sign up to request clarification or add additional context in comments.

Comments

1

Use glob function.

For example, if you have folder structure like this:

folder
    |----- autopass2.jpg
    |----- autopass3.png
    |----- auto_pass2.jpg
    |----- otherfile.xml

Now just use glob function with asterisk:

$result = glob('folder/autopass*');

And result is:

array
(
    0 => 'folder/autopass2.jpg'
    1 => 'folder/autopass3.png'
)

1 Comment

Thanks so much this explained it very well, i was just using the glob function like an idiot it seems.
1

glob can be used to find filenames starting with a specific string by using an asterisk as a wildcard:

scandir('cars');

Array
(
    [0] => .
    [1] => ..
    [2] => cars_convertible1.jpg
    [3] => cars_hatchback1.jpg
    [4] => cars_hatchback2.jpg
)

glob('cars/cars_hatchback*');

Array
(
    [0] => cars/cars_hatchback1.jpg
    [1] => cars/cars_hatchback2.jpg
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.