PHP RegEx匹配到字符串结尾

时间:2010-10-19 04:15:48

标签: php regex

仍在学习PHP正则表达式,并有一个问题。

如果我的字符串是

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

如何匹配(hh:mm:ss.ms):之后显示的值?

00:00:00.156

如果值后面有更多字符,我知道如何匹配,但之后没有更多字符,我不想包含尺寸信息。

提前致谢!

2 个答案:

答案 0 :(得分:8)

像这样:

<?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";
}
?>

这给出了:

captured: 00:00:00.156

答案 1 :(得分:0)

$将正则表达式锚定到字符串的末尾:

<?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]);
}

输出:

string(12) "00:00:00.156"