PHP计数,每2个字符添加冒号 [英] PHP count, add colons every 2 characters

查看:1117
本文介绍了PHP计数,每2个字符添加冒号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字符串

  1010081-COP-8-27-20110616214459 

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



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



所以在从最后计数6个字符后, p>

  214459 

添加冒号后,它将如下所示:

  21:44:59 


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



谢谢

解决方案

href =http://us2.php.net/manual/en/function.substr.php =nofollow> substr str_split implode



为了清楚起见,代码在多行上完成,但可以很容易在一行的链中完成:

  $ str ='1010081-COP-8-27-20110616214459'; 
//获取最后6个字符
$ end = substr($ str,-6);
//将字符串拆分成数组。每个元素是2个字符
$ chunks = str_split($ end,2);
//将数组转换为字符串。每个元素由给定的分隔符分隔。
$ result = implode(':',$ chunks);


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

解决方案

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);

这篇关于PHP计数,每2个字符添加冒号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆