This is my first time using the trim function and I want to get the Time excluding the open and close parenthesis of my string. Can you give me hints and suggestions on how to do this?
$string = "Updated by Carewina Almonte (04/02/2018 21:58:32)";
echo trim($string, "Updated by Carewina Almonte (04/02/2018");
exit();
You can use preg_match
for this task:
$str = 'Updated by Carewina Almonte (04/02/2018 21:58:32)';
preg_match('/(?<=\(\d{2}\/\d{2}\/\d{4} ).*(?=\))/', $str, $match);
echo $match[0];
Breakdown:
Positive Lookbehind (?<=\()
. Assert that the Regex below matches:
\(
matches the character (
literally (case sensitive).*
matches any character (except for line terminators)*
Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)\d{2}
matches a digit (equal to [0-9]
){2}
Quantifier — Matches exactly 2
times\/
matches the character /
literally (case sensitive)Positive Lookahead (?=\))
. Assert that the Regex below matches:
\)
matches the character )
literally (case sensitive)$string = "Updated by Carewina Almonte (04/02/2018 21:58:32)";
if(preg_match("/\d{2}:\d{2}:\d{2}/", $string , $match))
{
echo $match[0];
}
Regular expression should be used in this case.
In php, You can do get this and this works if and only if date and time always appears at the end of string -
$string = "Updated by Carewina Almonte (04/02/2018 21:58:32)";
$time = substr($string,-9,8);
echo $time;
For you example string you might match what is between parenthesis using \(\K[^)]+(?=\))
.
This will match an opening parenthesis \(
and then use \K
to reset the starting point of the reported match.
After that match NOT a closing parenthesis one or more times [^)]+
and a positive lookahead to assert that what follows is a closing parenthesis (?=\))
.
Then you could create a DateTime using or use DateTime::createFromFormat using $matches[0]
and extract the time:
$re = '/\(\K[^)]+(?=\))/';
$str = 'Updated by Carewina Almonte (04/02/2018 21:58:32)';
preg_match($re, $str, $matches);
$dateTime = new DateTime($matches[0]);
if ($dateTime !== false) {
echo $dateTime->format('H:i:s');
}