Let’s come to using these useful operations on PHP. We will introduce a few useful functions for this.
With the preg_match
function, we can check that the expression we wrote does not match the content we provide. In the example we will check if the input has a valid time format.
<?php
$pattern= '/^([01][0-9]|[2][0-3]):[0-5][0-9]:[0-5][0-9]$/';
$content = '23:15:59';
if(preg_match($pattern, $content))
{
echo 'A correct time has been entered.';
}
else
{
echo 'An incorrect time format has been entered.';
}
Returns true
if expression matches in text, otherwise false
.
If you are also curious about the explanation of the expression we wrote;
First, we denoted the beginning of the text with ^
, so it should start exactly as we wanted it to. Finally, we used $
, so we stated that we were looking for content that had exactly the beginning and end we wanted.
We then grouped ([01] [0-9] | [2] [0-3])
2 expressions. Because the time can be either from 01
to 19
or from 20
to 23
. If we said match 2 numbers between 0
and 9
in the form [0-9]{2}
, it would also match numbers greater than 23
, such as 99
.