PHP RegEx 匹配到字符串的结尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3965281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP RegEx Match to end of string
提问by Dave Kiss
Still learning PHP Regex and have a question.
仍在学习 PHP Regex 并有一个问题。
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):
?
如何匹配出现在 之后的值(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!
提前致谢!
回答by Jeremy W. Sherman
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
回答by meagar
$
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"