将字符串格式化为适当的 UTC 偏移量

发布于 2024-11-29 21:19:43 字数 243 浏览 3 评论 0原文

我有这样的字符串:

-4:00
3:15
+8:30

我需要将它们格式化为 UTC 偏移值,例如:

-0400
+0315
+0815

如何将示例字符串转换为最终字符串?我知道它可能使用了 str_replacesprintf 的一些组合,但我无法解决。

谢谢!

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我一向站在原地 2024-12-06 21:19:43

对我来说,这看起来像是一个非常简单的重新格式化(演示):

$offset = vsprintf('%+03d%02d', sscanf($offset, '%d:%d'));

0 被处理作为正数(++0000)。

This looks like a pretty simple re-formatting to me (Demo):

$offset = vsprintf('%+03d%02d', sscanf($offset, '%d:%d'));

0 is treated as positive number (+ as in +0000).

皇甫轩 2024-12-06 21:19:43

首先,检查输入字符串是否匹配。如果是,则从结果中删除整个匹配字符串,如果只有两部分,则缺少前导符号。在本例中,请在开头添加一个加号,并将小时填充到长度 2。最后将该数组转换为字符串。

foreach (array('-1:50','1:50','+1:50','-12:00','12:00','+12:00') as $input) {
  echo $input . ': ';

  if (preg_match('/^([-+])?([1-9][0-9]?):([0-9]{2})$/DX', $input, $asMatch) === 1) {
    unset($asMatch[0]);
    if ($asMatch[1] === '') {
      array_unshift($asMatch, '+');
    }
    $asMatch[2] = str_pad($asMatch[2], 2, '0', STR_PAD_LEFT);
    echo implode('', $asMatch);
  }

  echo "\n";
}

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.

foreach (array('-1:50','1:50','+1:50','-12:00','12:00','+12:00') as $input) {
  echo $input . ': ';

  if (preg_match('/^([-+])?([1-9][0-9]?):([0-9]{2})$/DX', $input, $asMatch) === 1) {
    unset($asMatch[0]);
    if ($asMatch[1] === '') {
      array_unshift($asMatch, '+');
    }
    $asMatch[2] = str_pad($asMatch[2], 2, '0', STR_PAD_LEFT);
    echo implode('', $asMatch);
  }

  echo "\n";
}
你怎么敢 2024-12-06 21:19:43

这里分三步:

$offset = preg_replace('/:/','',$offset);
$offset = preg_replace('/\b(?=\d{3}$)/', '0', $offset);
$offset = preg_replace('/^(?=\d)/m', '+', $offset);

如果您一次只传递一个偏移量,则可以删除第二个正则表达式上的 m 标志。

In three steps here it is:

$offset = preg_replace('/:/','',$offset);
$offset = preg_replace('/\b(?=\d{3}$)/', '0', $offset);
$offset = preg_replace('/^(?=\d)/m', '+', $offset);

You can remove the m flag on the second regex if you are only passing one offset at a time.

属性 2024-12-06 21:19:43

您想要支持的输入格式的一组正则表达式替换可能是最具可读性和可维护性的。

A set of regex substitutions for the input formats you want to support would probably be the most readable and maintainable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文