将字符串格式化为适当的 UTC 偏移量
我有这样的字符串:
-4:00
3:15
+8:30
我需要将它们格式化为 UTC 偏移值,例如:
-0400
+0315
+0815
如何将示例字符串转换为最终字符串?我知道它可能使用了 str_replace
和 sprintf
的一些组合,但我无法解决。
谢谢!
I have strings like:
-4:00
3:15
+8:30
I need to format them as UTC offset values like:
-0400
+0315
+0815
How can I convert the sample strings to the final strings? I know it probably uses some combo of str_replace
and sprintf
, but I cannot work it out.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对我来说,这看起来像是一个非常简单的重新格式化(演示):
0
被处理作为正数(+
如+0000
)。This looks like a pretty simple re-formatting to me (Demo):
0
is treated as positive number (+
as in+0000
).首先,检查输入字符串是否匹配。如果是,则从结果中删除整个匹配字符串,如果只有两部分,则缺少前导符号。在本例中,请在开头添加一个加号,并将小时填充到长度 2。最后将该数组转换为字符串。
First, check if the input string matches. If it does, remove the whole matching string from the result, and if there are only two parts, the leading sign is missing. In this case, add a plus in the beginning and pad the hour to a length of 2. Finally convert that array into a string.
这里分三步:
如果您一次只传递一个偏移量,则可以删除第二个正则表达式上的
m
标志。In three steps here it is:
You can remove the
m
flag on the second regex if you are only passing one offset at a time.您想要支持的输入格式的一组正则表达式替换可能是最具可读性和可维护性的。
A set of regex substitutions for the input formats you want to support would probably be the most readable and maintainable.