How can regular expressions (preg_match) be used to validate and extract components from a file name in PHP?
Regular expressions (preg_match) can be used in PHP to validate and extract components from a file name by defining a pattern that matches the desired format of the file name. This pattern can include specific characters, numbers, or formats that the file name should adhere to. By using preg_match, you can check if a file name matches the defined pattern and extract specific components such as the file extension or parts of the file name.
$filename = "example_file_2022.txt";
// Define a pattern to match a file name with the format "example_file_year.extension"
$pattern = '/^example_file_(\d{4})\.txt$/';
// Check if the file name matches the pattern
if (preg_match($pattern, $filename, $matches)) {
// Extract the year from the file name
$year = $matches[1];
echo "The file name matches the pattern. Year: $year";
} else {
echo "The file name does not match the pattern.";
}