Example 1 — Keep File Names Ending in .txt
Filter a small list of file names with a pattern.
<?php
$files = ['a.txt', 'b.jpg', 'c.txt', 'd.png'];
$txt = preg_grep('/\.txt$/', $files);
print_r($txt); How It Works
- The pattern /\. txt$/ means “ends with .txt”. The dots need escaping in regex.
- preg_grep() tests each array value against that pattern.
- a. txt and c.txt match, so they stay in the result.
- Original keys 0 and 2 are kept so you know which items matched.

