Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

how to make a filter function-filter out items in array?

1 view
Skip to first unread message

J. Frank Parnell

unread,
Nov 4, 2009, 6:02:51 PM11/4/09
to
tried this, but didnt work for more than one $delete. I understand
why, but not how to fix.

function arrayfilterout ($input, $delete) {
foreach($input as $i){
foreach($delete as $d){
if(strpos($i, $d)===false){
$newra[] = $i;//doesnt work here
}
}
}
return $newra;
}

$files= array('file.jpg','file.gif','file.doc','file.wmv');
$delete= array ('doc','wmv');

$pics = arrayfilterout ($files, $delete);

I want $pics to be jpgs and gifs only. Please dont take this example
literally, i need the strpos type filter.

thanks
J


Jerry Stuckle

unread,
Nov 4, 2009, 7:15:04 PM11/4/09
to

The way you have it written, it will add the file to the new array if
ANY of the tests are false. What you want is to add the file only if
ALL of the tests are false. One way:

function arrayfilterout ($input, $delete) {
$newra = array(); // Initialize the array!
foreach($input as $i){
$add = true; // Assume the file will be added
foreach($delete as $d){
if(strpos($i, $d)===true){
$add = false; // Match - do not add
break; // Match found, no further need to loop
}
}
if ($add) { // If no match was found
$newra[] = $input;
}
}
return $newra;
}

WARNING! DO NOT TRUST THE FILE EXTENSION IF IT IS A USER-UPLOADED FILE!

This also has other problems - like what happens if your file name is
something like 'mydoc.jpg'? Or 'my.doc.jpg'? Both will be incorrectly
filtered out.

--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstu...@attglobal.net
==================

crim...@googlemail.com

unread,
Nov 4, 2009, 8:43:18 PM11/4/09
to
On 5 ноя, 01:02, "J. Frank Parnell" <jugl...@gmail.com> wrote:

> $files= array('file.jpg','file.gif','file.doc','file.wmv');
> $delete= array ('doc','wmv');
>
> $pics = arrayfilterout ($files, $delete);
>
> I want $pics to be jpgs and gifs  only.  Please dont take this example
> literally, i need the strpos type filter.

You need array_filter() and preg_match() functions. And think about
cases like 'jpg_list.doc' or 'doc.jpg.wmv'.
I think you need mask like '/\\.('.join('|',$delete).')$/i'

J. Frank Parnell

unread,
Nov 6, 2009, 5:32:48 PM11/6/09
to
On Nov 4, 5:43 pm, "criman...@googlemail.com"

Great, thanks guys :)

0 new messages