2
Exercise 1• Write a regular expression that will match a time/clock
hh:mm:ss pattern.
Examples: • "00:00:15" is valid• "0:56:25" is not valid• “11:15:09" is valid• "15:96:22" is not valid
Solution: /([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/
Solving …
Solution2: /([01]\d|2[0-3]):([0-5]\d):([0-5]\d)/
3
Exercise 1 - Solution// time
echo "Example Time <br>";
$subject="00:00:15 0:56:25 95:00:25 11:15:09 15:96:22 20:15:10 ";
$pattern = "/([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/";
if (preg_match_all($pattern, $subject, $result, PREG_OFFSET_CAPTURE)):
echo "$pattern was found: \n";
print_r($result);
nl();
endif;
4
Exercise 1 - Solution
Time Accept?
00:00:15 Yes
0:56:25 No
95:00:25 No
11:15:09 Yes
15:96:22 No
20:15:10 Yes
Run Program … Click
5
Exercise 1 - Report/AnswersArray ( [0] => Array (
[0] => Array ( [0] => 00:00:15 [1] => 0 )
[1] => Array ( [0] => 11:15:09 [1] => 26 )
[2] => Array ( [0] => 20:15:10 [1] => 44 )
)
[1] => Array (
[0] => Array ( [0] => 00 [1] => 0 )
[1] => Array ( [0] => 11 [1] => 26 )
[2] => Array ( [0] => 20 [1] => 44 )
)
[2] => Array (
[0] => Array ( [0] => 00 [1] => 3 )
[1] => Array ( [0] => 15 [1] => 29 )
[2] => Array ( [0] => 15 [1] => 47 )
)
[3] => Array (
[0] => Array ( [0] => 15 [1] => 6 )
[1] => Array ( [0] => 09 [1] => 32 )
[2] => Array ( [0] => 10 [1] => 50 )
)
)
6
Exercise 2• Write a regular expression that will match a zip code. The
zip pattern may be like "16059" or the expanded form of "15221-2397". If there is a dash after the 5 digits then there must follow exactly 4 digits.
Examples: • "15221-abcd " is not valid• "12345 " is valid• “12345-1234" is valid• “12345-123“ is not valid
Solution: /\d{5}(-\d{4})?/
Solving …
7
Exercise 2 - Solution//zip code
echo "Example Zip-code <br>";
$subject="15221-abcd 12345 12345-123 12345-1234 1235 54263 54263-4321";
$pattern = "/\d{5}(-\d{4})?/";
if (preg_match_all($pattern, $subject, $result, PREG_OFFSET_CAPTURE)):
echo "$pattern was found: \n";
print_r($result);
nl();
endif;
8
Exercise 2 - Solution
Zip Code Accept?
15221-abcd No
12345 Yes
12345-123 No
12345-1234 Yes
1235 No
54263 Yes
54263-4321 Yes
Run Program … Click
9
Exercise 2 – Report/AnswersArray ( [0] => Array (
[0] => Array ( [0] => 15221 [1] => 0 )
[1] => Array ( [0] => 12345 [1] => 11 )
[2] => Array ( [0] => 12345 [1] => 17 )
[3] => Array ( [0] => 12345-1234 [1] => 27 )
[4] => Array ( [0] => 54263 [1] => 43 )
[5] => Array ( [0] => 54263-4321 [1] => 49 )
)
[1] => Array (
[0] =>
[1] =>
[2] =>
[3] => Array ( [0] => -1234 [1] => 32 )
[4] =>
[5] => Array ( [0] => -4321 [1] => 54 )
)
)
10
Questions
Top Related