Regex Alternation

Summary: in this tutorial, you’ll learn about regex alternation, which is simply an “OR” operator in the regular expression.

Introduction to the regex alternation #

Regular expressions use the pipe character (|) to denote an alternation. The alternation is simple the OR operator in the regular expressions.

For example, the following pattern uses the alternation (|) to match apple or orange:

'/apple|orange/'

Here’s the code:

<?php

$str = "apple, orange, banana";
$pattern = '/apple|orange/';

if (preg_match_all($pattern, $str, $matches)) {
    print_r($matches[0]);
}

Try it

Output:

Array
(
    [0] => apple
    [1] => orange
)

Use the regex alternation for matching time in hh:mm format #

To match a time in hh:mm, you can use the following regular expression:

'/\d{2}:\d{2}/'

However, the\d{2} pattern also matches 99, which is not a valid hour or minute.

To fix this, you can use the regex alternation. The valid hour ranges from 01 to 23. Therefore, the pattern for matching the hour is as follows:

[01]\d|2[0-3]

The minute ranges from 00 to 59. So the pattern for the minute is:

[0-5]\d

Here’s the regular expression that matches the time in the hh:mm format:

'/[01]\d|2[0-3]:[0-5]\d/'

Also, you can add the capturing groups for both hour and minute:

'/([01]\d|2[0-3]):([0-5]\d)/'

The following example illustrates how to use the regex alternation to match the time:

<?php

$times = ['10:20', '24:10', '01:20', '22:99'];
$pattern = '/([01]\d|2[0-3]):([0-5]\d)/';

foreach ($times as $time) {
    if (preg_match($pattern, $time, $matches)) {
        echo $matches[0] . PHP_EOL;
    }
}

Try it

Output:

10:20
01:20

Summary #

  • The regex alternation is an OR operator in regular expressions.

Was this helpful?