简体   繁体   中英

PHP RegEx Match to end of string

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!

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

$ 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM