Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search string with array of values with PHP

Tags:

regex

php

I am trying to search a list of files and only perform work on the files that have names that contain a few values in an array. I am hoping to not have to loop through the array each time I have a new filename.
ala-

$needle = array('blah', 'bleh');
foreach($file_list as $file)
{
    foreach($needle as $need)
       if(strstr($file, $need) !== false)
          {
             // do something...
          }
}

I just need to know if one of the strings in the array is in the filename, not the location of the string.

I would like to use something similar to strstr() but it does not allow an array to be used as the needle.

i.e.-

if(strstr($haystack, array('blah', 'bleh')))
{
   // do something...
}

I would prefer to stay away from regular expressions, it seems to be a sledge for a hammer's job. any ideas?

like image 409
Patrick Avatar asked Jan 21 '23 20:01

Patrick


2 Answers

IMO it is fine to use regular expressions here:

$pattern  = '/' . implode('|', array_map('preg_quote', $needle)) . '/i';

foreach($file_list as $file) {
    if(preg_match($pattern, $file)) {
    // do something
    }
}

Reference: preg_quote


Here is a more "creative" way to do it (but it uses internal loops and is very likely slower, as you actually loop several times over the array):

function cstrstr($haystack, $needle) {
    return strstr($haystack, $needle) !== false;
}

foreach($file_list as $file) {
    if(array_sum(array_map('cstrstr', 
                       array_pad(array($file), count($needle), $file), 
                       $needle))) {
        // do something
    }
}

But the advantages with the regex should be obvious: You have to create the pattern only once whereas in the "funny" solution you always have to create an array of length count($needle) for every $file.

like image 67
Felix Kling Avatar answered Jan 30 '23 20:01

Felix Kling


Patrick,

You can use in_array(). Example:

foreach($file_list as $file){

   if(in_array($file, $needle)){
     //--------------
     // Needle found
   }
}

You can find more examples here: http://php.net/manual/en/function.in-array.php

like image 35
OV Web Solutions Avatar answered Jan 30 '23 20:01

OV Web Solutions