1

If my string is

Size : 93743 bytes Time elapsed (hh:mm:ss.ms): 00:00:00.156

How do I match the value that appears after the (hh:mm:ss.ms): ?

00:00:00.156

I know how to match if there are more characters following the value, but there aren't any more characters after it and I do not want to include the size information.

2 Answers 2

11

Like so:

<?php
$text = "Size : 93743 bytes Time elapsed (hh:mm:ss.ms): 00:00:00.156";

# match literal '(' followed by 'hh:mm:ss.ms' followed by literal ')'
# then ':' then zero or more whitespace characters ('\s')
# then, capture one or more characters in the group 0-9, '.', and ':'
# finally, eat zero or more whitespace characters and an end of line ('$')
if (preg_match('/\(hh:mm:ss.ms\):\s*([0-9.:]+)\s*$/', $text, $matches)) {
    echo "captured: {$matches[1]}\n";
}
?>

This gives:

captured: 00:00:00.156
Sign up to request clarification or add additional context in comments.

Comments

0

$ anchors the regex to the end of the string:

<?php
$str = "Size : 93743 bytes Time elapsed (hh:mm:ss.ms): 00:00:00.156";

$matches = array();

if (preg_match('/\d\d:\d\d:\d\d\.\d\d\d$/', $str, $matches)) {
  var_dump($matches[0]);
}

Output:

string(12) "00:00:00.156"

3 Comments

how about 00:00:00:1 or 00:00:00:22?
@Amarghosh Question didn't indicate that either of those are possible inputs; I assume the format would be ...00:100 and ...00:220 in those cases.
This still isn't working, not sure if there is some kind of extra space after the string or what... and yes, the format would be ...00:100 - is that to say $ tells the preg_match that it should stop looking at that point, or to continue looking until the end of the string? I think I need something that says to stop the match after the last \d

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.