PHP for determining if a string contains a valid time format


Code Solution

function isValidTime(string $time): bool {
  // Check if the time is in HH:MM format
  if (!preg_match('/^([0-1][0-9]|2[0-3]):[0-5][0-9]$/', $time)) {
    return false;
  }

  // Extract the hours and minutes from the time
  list($hours, $minutes) = explode(':', $time);

  // Check if the hours and minutes are valid
  if ($hours < 0 || $hours > 23 || $minutes < 0 || $minutes > 59) {
    return false;
  }

  return true;
}

Explanation

This PHP code solution provides a function called isValidTime that checks if a given string contains a valid time format. A valid time format in this case is considered to be in the HH:MM pattern, where HH represents the hour (00-23) and MM represents the minutes (00-59).

How it Works

  1. Pattern Matching: The code first uses a regular expression to check if the input string matches the HH:MM format. It ensures that the string has exactly two parts separated by a colon (:), with the first part representing hours (0-19 or 20-23) and the second part representing minutes (0-59). If the string doesn’t match this pattern, it returns false.
  2. Extraction of Hours and Minutes: If the pattern matching succeeds, the code extracts the hours and minutes from the input string using the explode function. The explode function splits the string into an array based on the given delimiter (in this case, a colon).
  3. Validity Check: The code then checks if the extracted hours and minutes are within valid ranges. It ensures that the hours are between 0 and 23 (inclusive) and that the minutes are between 0 and 59 (inclusive). If either the hours or minutes are outside these ranges, the function returns false.
  4. Return Value: If both the pattern matching and the validity checks pass, the function returns true, indicating that the input string contains a valid time format.

Implementation

To use this code solution effectively, you can incorporate the isValidTime function into your PHP application or script. Here’s an example of how you might use it:

$time = '12:30';
if (isValidTime($time)) {
  echo "The time '$time' is in a valid format.";
} else {
  echo "The time '$time' is not in a valid format.";
}

In this example, we check the validity of the time string ’12:30′ using the isValidTime function. If the function returns true, it indicates that ’12:30′ is a valid time format, and if it returns false, it indicates that ’12:30′ is not a valid time format.