tags:

views:

34

answers:

3

Hi all,

Still learning PHP Regex and have a question.

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.

Thanks in advance!

A: 

$ 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"
meagar
how about `00:00:00:1` or `00:00:00:22`?
Amarghosh
@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.
meagar
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`
Dave Kiss
A: 
'/\d{2}:\d{2}:\d{2}\.\d{3}$/'
Phil Brown
+3  A: 

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
Jeremy W. Sherman
Perfect, thanks a ton!
Dave Kiss