PHP计数,每2个字符添加冒号

发布于 2024-11-16 03:14:17 字数 312 浏览 3 评论 0原文

我有这个字符串,

1010081-COP-8-27-20110616214459

我需要计算从该字符串末尾开始的最后 6 个字符(因为从头开始可能很长)

然后我需要在每 2 个字符后添加冒号。

因此,从末尾算起 6 个字符后,它会是

214459

添加冒号后,它看起来像:

21:44:59

你能帮我实现它吗?

我真的不知道从哪里开始!

谢谢

I have this string

1010081-COP-8-27-20110616214459

I need to count the last 6 characters starting from the end of this string (because it could may be long starting from the begin)

Then I need to add colons after every 2 characters.

So after counting 6 characters from the end it will be

214459

After having added the colons it will look like:

21:44:59

Can you help me achieving it?

I do not really know where to start!

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

过期情话 2024-11-23 03:14:17

您可以使用 substr 来完成此操作, str_splitimplode

代码分多行完成清晰,但可以轻松地在一行中完成:

$str = '1010081-COP-8-27-20110616214459';
//Get last 6 chars
$end = substr($str, -6);
//Split string into an array.  Each element is 2 chars
$chunks = str_split($end, 2);
//Convert array to string.  Each element separated by the given separator.
$result = implode(':', $chunks);

You can do this with substr, str_split and implode

The code is done on multiple lines for clarity, but can easily be done in a chain on one line:

$str = '1010081-COP-8-27-20110616214459';
//Get last 6 chars
$end = substr($str, -6);
//Split string into an array.  Each element is 2 chars
$chunks = str_split($end, 2);
//Convert array to string.  Each element separated by the given separator.
$result = implode(':', $chunks);
倾其所爱 2024-11-23 03:14:17
echo preg_replace('/^.*(\d{2})(\d{2})(\d{2})$/', '$1:$2:$3', $string);

在我看来,该字符串具有特定的格式,您应该将其解析为数据。像这样的东西:

sscanf($string, '%u-%3s-%u-%u-%u', $id, $type, $num, $foo, $timestamp);
$timestamp = strtotime($timestamp);
echo date('Y-m-d H:i:s', $timestamp);
echo preg_replace('/^.*(\d{2})(\d{2})(\d{2})$/', '$1:$2:$3', $string);

It looks to me though like that string has a particular format which you should parse into data. Something like:

sscanf($string, '%u-%3s-%u-%u-%u', $id, $type, $num, $foo, $timestamp);
$timestamp = strtotime($timestamp);
echo date('Y-m-d H:i:s', $timestamp);
脱离于你 2024-11-23 03:14:17

如果你只想要时间:

$time = rtrim(chunk_split(substr($s,-6),2,':'),':');

If you just want the time:

$time = rtrim(chunk_split(substr($s,-6),2,':'),':');
梦初启 2024-11-23 03:14:17
$final = "1010081-COP-8-27-20110616214459";

$c = substr($final, -2);
$b = substr($final, -4, 2);
$a = substr($final, -6, 2);

echo "$a:$b:$c"; 
$final = "1010081-COP-8-27-20110616214459";

$c = substr($final, -2);
$b = substr($final, -4, 2);
$a = substr($final, -6, 2);

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