使用PHP将多个数字更改为另一个数字

时间:2015-12-28 09:36:15

标签: php replace str-replace

在文字中,我有很多时间码,然后我想将小时改为另一个时区(+6),例如:

00:15 => 6时15分

01:00 => 07:00

......等等。 我试过这个:

$result = str_replace(
  array("00:","01:","02:","03:","04:","05:","06:","07:","08:","09:","10:","11:","12:","13:","14:","15:","16:","17:","18:","19:","20:","21:","22:","23:"),
    array("06:","07:","08:","09:","10:","11:","12:","13:","14:","15:","16:","17:","18:","19:","20:","21:","22:","23:","00:","01:","02:","03:","04:", "05:"),
    $text
);
 echo $result;

但是18:将替换为04:因为php替换18​​:到22:然后继续替换22:到04:

如何解决这个问题,谢谢。

// 编辑:要@ user3414969和@ Medda86:$ text是我从其他网站获取的数据,这意味着我无法控制来源,唯一的方法是取代

// 编辑2 :以下是内容:http://bongdatv.net/test.php

// 编辑3 :请用替换方式解决此问题,而不是计算方式。

4 个答案:

答案 0 :(得分:1)

我认为最好是使用时间戳格式,添加时间并从中获取新的时间。

http://php.net/manual/en/function.time.php

答案 1 :(得分:1)

$time = array("00:","01:","02:","03:","04:","05:","06:","07:","08:","09:","10:","11:","12:","13:","14:","15:","16:","17:","18:","19:","20:","21:","22:","23:");

$required_time = array();
    
foreach($time as $t){
    $hour = $t."00"; // 00 appending 0 minites
    $hours_plus = 6; // adding 6 hours
    $required_time[] = date('H:', strtotime($hour)+($hours_plus*60*60));
}
echo "<pre>";
    print_r($required_time);
    echo "</pre>";

答案 2 :(得分:0)

最佳方式如Medda86所示 但是,您可以尝试这种方式

$array = ("00:","01:",....);
//Then you can loop over array and add the time 
for($i=0 ; $i < sizeof($array);$i++){
       $array[$i] = intval($array[$i]+6)%24;
       if($array[$i] < 10)
         $array[$i] = str_pad($array[$i],2,'0',STR_PAD_LEFT).':';
       else
         $array[$i] .= ':';
}

答案 3 :(得分:0)

试试这个:

$yourArr = array('00:15','01:00','00:30');
foreach ($yourArr as $key => $value) {
    $timestamp = strtotime($value) + 60*60*6; // add hours as per your need.
    $time = date('H:i', $timestamp);
    $newArr[] = $time;
}
echo "<pre>";
print_r($newArr);

结果是:

Array
(
    [0] => 06:15
    [1] => 07:00
    [2] => 06:30
)