帮助解析格式化字符串
我有字符串:
17s 283ms
48s 968ms
字符串值永远不会相同,我想从中提取“第二个”值。在本例中,是 17 和 48。
我不太擅长正则表达式,所以我所做的解决方法是这样的:
$str = "17s 283ms";
$split_str = explode(' ', $str);
foreach($split_str as $val){
if(strpos($val, 's') !== false) $sec = intval($val);
}
问题是,字符 's' 存在于 split_str[0] 中和 split_str[1],所以我的 $sec 变量不断获得 283,而不是 17。
同样,我不太擅长正则表达式,而且我很确定正则表达式是这种情况下的最佳选择。请帮忙。谢谢。
I have strings:
17s 283ms
48s 968ms
The string values are never the same and I want to extract the "second" value from it. In this case, the 17 and the 48.
I'm not very good with regex, so the workaround I did was this:
$str = "17s 283ms";
$split_str = explode(' ', $str);
foreach($split_str as $val){
if(strpos($val, 's') !== false) $sec = intval($val);
}
The problem is, the character 's' exists in both split_str[0] and split_str[1], so my $sec variable keeps obtaining 283, instead of 17.
Again, I'm not very good with regex, and I'm pretty sure regex is the way to go in this case. Please assist. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您甚至不需要为此使用正则表达式。
上述解决方案将从字符串开头提取所有数字。第一个非数字字符是“s”、空格还是其他任何字符都没关系。
但何苦呢?
您甚至可以将
$str
转换为int
:查看实际操作。
正则表达式对于这样一个简单的任务来说绝对是大材小用。请勿使用炸药在墙上钻孔。
You don't even need to use regex for this.
The above solution will extract all the digits from the beginning of the string. Doesn't matter if the first non-digit character is "s", a space, or anything else.
But why bother?
You can even just cast
$str
to anint
:See it in action.
Regular expressions are definite overkill for such a simple task. Don't use dynamite to drill holes in the wall.
你可以这样做:
You could do this like so:
如果字符串始终以这种方式格式化,您可以简单地使用:
If the string will always be formatted in this manner, you could simply use:
好吧,我想你可以假设秒总是在毫秒之前。如果格式一致,则不需要正则表达式。这应该可以做到:
这将按空格分割字符串并获取第一部分
17s
。然后使用 rtrim 删除 's',剩下17
。Well, i guess that you can assume seconds always comes before milliseconds. No need for regexp if the format is consistent. This should do it:
This will split the string by space and take the first part
17s
. rtrim is then used to remove 's' and you're left with17
.(\d+s) \d+ms
是正确的正则表达式。用法如下:
那么,ms 之前的号码将是
$groups[1]
。(\d+s) \d+ms
is the right regexp. Usage would be something like this:
Then, your number before ms would be
$groups[1]
.