Value Filter Array

I am using PHP and I have an array of custom images that I need to filter. I need to make two different filters:

  • Look in the source array and see if each value contains a value in the bad words array
  • Look and see if the value in the source array ended with one of the "bad extensions" values

Array of images:

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 him to return:

Array  
(  
    [0] => kittens.jpg  
    [1] => biscuits.png  
)  
+3
source share
3 answers
$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 deleted. from your tho extensions

edit: added evil flea correction

+4
source

-, . . , () , ,

$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 .

- PHP

+1

You can use the array_filter function in PHP, just write a function that does the filtering and then call

array_filter($array1, "custom_filter");
0
source

Source: https://habr.com/ru/post/1721452/


All Articles