4

I have an array of filenames which I need to check against a code, for example

array("120_120_435645.jpg","150_150_312312.jpg","250_250_1232327.jpg");

the string is "312312" so it would match "150_150_312312.jpg" as it contains that string. If there are no matches at all within the search then flag the code as missing.

I tried in_array but this seems to any return true if it is an exact match, don't know if array_filter will do it wither...

Thanks for any advice...perhaps I have been staring at it too long and a coffee may help :)

3
  • 1
    stackoverflow.com/a/5592142/138383 Commented Aug 20, 2013 at 15:24
  • I'd rather use stripos rather than preg_ functions Commented Aug 20, 2013 at 15:39
  • The point is that you don't need a loop by using preg_grep. Commented Aug 20, 2013 at 15:58

1 Answer 1

17
$filenames = array("120_120_435645.jpg","150_150_312312.jpg","250_250_1232327.jpg");
$matches = preg_grep("/312312/", $filenames);
print_r($matches);

Output:

Array
(
    [1] => 150_150_312312.jpg
)

Or, if you don't want to use regex, you can simply use strpos as suggested in this answer:

foreach ($filenames as $filename) {
    if (strpos($filename,'312312') !== false) {
    echo 'True';
    }
}

Demo!

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.