Reputation: 2207
So I have an array with values, this case file extentions but i'm using preg_match to filter out file extentions that are not allowed.
Is there an easy way to translate an array to an regex pattern?
Source array
(
[1] => 'file-to-path/thumbs/allowedfile.pdf',
[2] => 'file-to-path/thumbs/notallowedfile.psd',
[3] => 'file-to-path/project/test/notallowedfile.txt',
)
Allowed extentions array
(
[0] => bmp
[1] => jpg
[2] => jpeg
[3] => gif
...
)
The code that im using right now.
foreach($array as $key => $val){
if( !preg_match('/^.*\.(jpg|png|jpeg|bmp|gif|pdf)$/i', $val ) ){
// this part needs to be an array
'/^.*\.(jpg|png|jpeg|bmp|gif|pdf)$/i' -> [array with the values]
}
}
Upvotes: 0
Views: 127
Reputation:
all not allowed files you can quick ignore them with minimum cpu use
function check(){
$who = array(
1 => 'file-to-path/thumbs/allowedfile.pdf',
2 => 'file-to-path/thumbs/notallowedfile.psd',
3 => 'file-to-path/project/test/notallowedfile.txt'
);
return preg_grep('/^.*\.(jpg|png|jpeg|bmp|gif|pdf)$/i', $who );
}
print_r(check());
In my browser, I got this push Run Code Snippet:
Array
(
[1] => file-to-path/thumbs/allowedfile.pdf
)
or
function check($who){
return preg_grep('/^.*\.(jpg|png|jpeg|bmp|gif|pdf)$/i', $who );
}
print_r(check(array(
1 => 'file-to-path/thumbs/allowedfile.pdf',
2 => 'file-to-path/thumbs/notallowedfile.psd',
3 => 'file-to-path/project/test/notallowedfile.txt'
)));
Upvotes: 0
Reputation: 46610
I would avoid regex for this, and use pathinfo($value, PATHINFO_EXTENSION)
and in_array()
For example, which populates an $error
array and filters your array.
<?php
$allowed_ext = array (
'bmp',
'jpg',
'jpeg',
'gif',
'pdf'
);
$files = array(
1 => 'file-to-path/thumbs/allowedfile.pdf',
2 => 'file-to-path/thumbs/notallowedfile.psd',
3 => 'file-to-path/project/test/notallowedfile.txt'
);
$errors = [];
foreach ($files as $key => $value) {
if (!in_array(pathinfo($value, PATHINFO_EXTENSION), $allowed_ext)) {
$errors[] = basename($value).' is not allowed.';
unset($arr[$key]);
}
}
print_r($errors);
print_r($files);
Result:
Array
(
[0] => notallowedfile.psd is not allowed.
[1] => notallowedfile.txt is not allowed.
)
Array
(
[1] => file-to-path/thumbs/allowedfile.pdf
)
If you just want to filter the array, then you can use array_filter()
$files = array_filter($files, function ($file) use ($allowed_ext) {
return in_array(pathinfo($file, PATHINFO_EXTENSION), $allowed_ext);
});
Upvotes: 2
Reputation: 1833
You can use array_filter function then check the extension of a single file in the list of available extensions, and return true if it's valid extension otherwise returns false and it's exclude.
$validFiles = array_filter($files, function ($file) use ($key, $value, arrOfValidExtensions) {
$fileExtenstion = getFileExtension($value); //Implement this function to return the file extension
return in_array($fileExtension, $arrOfValidExtensions);
});
Upvotes: 0