1. <?php
  2. /**
  3. * Replaces time values for validation checks.
  4. *
  5. * @param string $time_value The time value string (e.g., '10:30:00').
  6. * @param string $replacement_value The replacement time value string (e.g., '00:00:00').
  7. * @param string $format The format of the time value (e.g., 'H:i:s').
  8. * @return string The replaced time value string, or the original value if the input is invalid.
  9. */
  10. function replaceTimeForValidation(string $time_value, string $replacement_value, string $format = 'H:i:s'): string
  11. {
  12. // Validate input parameters
  13. if (empty($time_value) || empty($replacement_value) || empty($format)) {
  14. return $time_value; // Return original if any input is empty.
  15. }
  16. // Attempt to create a DateTime object. Handle potential errors gracefully.
  17. try {
  18. $original_datetime = new DateTime($time_value);
  19. } catch (Exception $e) {
  20. return $time_value; // Return original if parsing fails.
  21. }
  22. // Create a new DateTime object with the replacement value.
  23. $new_datetime = new DateTime($replacement_value);
  24. // Format the new DateTime object back to the original format.
  25. return $new_datetime->format($format);
  26. }
  27. //Example Usage
  28. // $time = "14:45:12";
  29. // $replaced_time = replaceTimeForValidation($time, "00:00:00");
  30. // echo $replaced_time . "\n";
  31. ?>

Add your comment