What is the best method to extract values from a file name in PHP?

When working with file names in PHP, you may need to extract specific values from the file name for further processing. One common method to achieve this is by using regular expressions to match and extract the desired values from the file name. Regular expressions allow you to define patterns that can be used to search for and extract specific substrings from a given string, such as a file name.

// Example file name: "document_2022-01-15.pdf"
$filename = "document_2022-01-15.pdf";

// Define a regular expression pattern to match the date in the file name
$pattern = '/(\d{4}-\d{2}-\d{2})/';

// Use preg_match to extract the date from the file name
if (preg_match($pattern, $filename, $matches)) {
    $date = $matches[0];
    echo "Date extracted from file name: " . $date;
} else {
    echo "Date not found in file name";
}