What are some best practices for parsing and extracting multiple date ranges from a string in PHP, especially when the number of ranges is variable?

When parsing and extracting multiple date ranges from a string in PHP, especially when the number of ranges is variable, it is best to use regular expressions to match and extract the date ranges. By using regular expressions, you can define patterns to identify date ranges in the string and extract them accordingly. Additionally, it is important to handle cases where the date ranges may be in different formats or separated by different delimiters.

<?php
$string = "Event from 2022-01-01 to 2022-01-10 and another event from 2022-02-15 to 2022-02-20";

$pattern = '/\b\d{4}-\d{2}-\d{2}\b/';

preg_match_all($pattern, $string, $matches);

$dateRanges = array_chunk($matches[0], 2);

foreach ($dateRanges as $range) {
    $startDate = $range[0];
    $endDate = $range[1];
    
    echo "Start Date: $startDate, End Date: $endDate\n";
}
?>