我有这个字符串
1010081-COP-8-27-20110616214459
我需要从这个字符串的末尾开始计算最后6个字符(因为从开头开始可能很长)
然后我需要在每2个字符后添加冒号。
因此,从最后算起6个字符后,它将是
214459
添加冒号后,它将看起来像:
21:44:59
你能帮我实现它吗?
我真的不知道从哪里开始!
感谢
您可以使用substr
、str_split
和implode
执行此操作
为了清晰起见,代码是在多行上完成的,但可以很容易地在一行上的链中完成:
$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);
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);
如果你只想要时间:
$time = rtrim(chunk_split(substr($s,-6),2,':'),':');
$final = "1010081-COP-8-27-20110616214459";
$c = substr($final, -2);
$b = substr($final, -4, 2);
$a = substr($final, -6, 2);
echo "$a:$b:$c";