I am using PHP and I have an array of user images that I need to filter. I need to do 2 different filters:
Images Array:
Array
(
[0] => smiles.gif
[1] => kittens.jpg
[2] => biscuits.png
[3] => butthead.jpg
)
$bad_words = array('beavis','butthead','winehouse');
$bad_extensions = array('.gif','.tiff');
I would like it to return:
Array
(
[0] => kittens.jpg
[1] => biscuits.png
)
$array = array("smiles.gif", "kittens.jpg", "biscuits.png", "butthead.jpg");
$new_arr = array_filter($array, "filter");
function filter($element) {
$bad_words = array('beavis','butthead','winehouse');
$bad_extensions = array('gif','tiff');
list($name, $extension) = explode(".", $element);
if(in_array($name, $bad_words))
return;
if(in_array($extension, $bad_extensions))
return;
return $element;
}
echo "<pre>";
print_r($new_arr);
echo "</pre>";
Outputs
Array
(
[1] => kittens.jpg
[2] => biscuits.png
)
I removed the . from your extensions tho
edit: added wicked fleas correction
Firstly, I'd remove the periods in your extension list. It will only make the code more difficult. If you've done this, the following (untested) code should work, or at least be a start
$cleanArray = [];
foreach($array as $value) {
$extension = path_info($value, PATHINFO_EXTENSION);
if (in_array($extension, $bad_extensions)) {
continue;
}
foreach($bad_words as $word) {
if (strstr($word, $value)) {
continue 2;
}
}
$cleanArray[] = $value;
}
$cleanArray should have the values you want.
Here are some handy references from the PHP online docs
您可以在PHP中使用array_filter函数,只需编写一个函数来执行您想要的过滤然后调用
array_filter($array1, "custom_filter");
Because case-insensitive matching is a reasonable inclusion and because in_array()
does not have a case-insensitive mode, I'd probably just generate a regex pattern from the two arrays and let the regex engine do the tedious filtration.
Code: ( Demo )
$branches = implode(
'|',
array_merge(
$bad_words,
array_map(
fn($v) => preg_quote($v, '/') . '$',
$bad_extensions
)
)
);
// beavis|butthead|winehouse|\.gif$|\.tiff$
var_export(preg_grep("/$branches/i", $array, PREG_GREP_INVERT));
Output:
array (
1 => 'kittens.jpg',
2 => 'biscuits.png',
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.