Skip to content
PHP Logo

What is the correct way to apply preg_match_all and regular expressions in PHP to filter out specific file extensions?

When using preg_match_all and regular expressions in PHP to filter out specific file extensions, you can create a regular expression pattern that matches the desired file extensions. You can then use preg_match_all to apply this pattern to a list of file names and extract only the ones with the specified extensions.

php
$files = ['file1.jpg', 'file2.txt', 'file3.png', 'file4.doc'];

$pattern = '/\.(jpg|png)$/i'; // Match file extensions jpg and png case-insensitively

preg_match_all($pattern, implode(',', $files), $matches);

$filteredFiles = $matches[0];

print_r($filteredFiles);