Oihana PHP Standards

isIso8601Duration.php

Table of Contents

Functions

isIso8601Duration()  : bool
Validates whether a string is a valid ISO 8601 duration format.

Functions

isIso8601Duration()

Validates whether a string is a valid ISO 8601 duration format.

isIso8601Duration(string $duration[, bool $strict = false ]) : bool

This function checks if a given string conforms to the ISO 8601 duration specification. The ISO 8601 duration format follows the pattern: P[n]Y[n]M[n]W[n]DT[n]H[n]M[n]S

Valid formats include:

  • Date components: P[n]Y[n]M[n]W[n]D (years, months, weeks, days)
  • Time components: PT[n]H[n]M[n]S (hours, minutes, seconds)
  • Combined: P[n]Y[n]M[n]DT[n]H[n]M[n]S
  • Zero duration: P0D, PT0S, P0Y, etc.

Rules:

  • Must start with 'P' (period designator)
  • 'T' separates date and time components (required if time components are present)
  • At least one component must be present
  • Components must be in correct order: Y, M, W/D, then T, then H, M, S
  • Negative durations are not part of ISO 8601 standard but PHP accepts them
Parameters
$duration : string

The duration string to validate

$strict : bool = false

If true, uses regex validation; if false, uses PHP's DateInterval parser (default: false)

Tags
example
validateIso8601Duration('P1Y2M3D'); // true
validateIso8601Duration('PT4H30M'); // true
validateIso8601Duration('P1W'); // true
validateIso8601Duration('P0D'); // true
validateIso8601Duration('INVALID'); // false
validateIso8601Duration('P'); // false (no components)
validateIso8601Duration('1Y2M'); // false (missing P)
// Strict mode validation (regex-based)
validateIso8601Duration('P1Y2M3D', true); // true
validateIso8601Duration('P1.5Y', true); // false (no decimals in strict mode)
// Form validation
if (!validateIso8601Duration($_POST['duration'])) {
    throw new Exception('Invalid duration format');
}
link

ISO 8601 Duration specification

PHP DateInterval constructor

author

Marc Alcaraz (ekameleon)

since
1.0.1
Return values
bool

True if the string is a valid ISO 8601 duration, false otherwise

On this page

Search results