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?
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With