如何将"1d2h3m"转换为数组("day"=> 1,"hour"=> 2,"minutes"=> 3)?

Dav*_*pan 10 php arrays date

$time = "1d2h3m";这样我想要这样的数组,array("day" => 1, ”hour” => 2,"minutes"=>3)所以我尝试了explode()

<?php
   $time = "1d2h3m";
   $day = explode("d", $time);
   var_dump($day); // 0 => string '1' (length=1)
                   // 1 => string '2h3m' (length=4)
?>
Run Code Online (Sandbox Code Playgroud)

在这里我不知道如何做数组 array("day" => 1, ”hour” => 2,"minutes"=>3)

use*_*918 25

一个简单的sscanf将解析为一个数组.然后array_combine使用您想要的键列表.

例:

$time = "1d2h3m";

$result = array_combine(
    ['day', 'hour', 'minutes'],
    sscanf($time, '%dd%dh%dm')
);

print_r($result);
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [day] => 1
    [hour] => 2
    [minutes] => 3
)
Run Code Online (Sandbox Code Playgroud)

要打破sscanf使用的格式:

  • %d - 读取(带符号)十进制数,输出整数
  • d - 匹配文字字符"d"
  • %d - (作为第一个)
  • h - 匹配文字字符"h"
  • %d - (作为第一个)
  • m - 匹配文字字符"m"(可选,因为它出现在您想要抓取的所有内容之后)

它也适用于多位数和负值:

$time = "42d-5h3m";
Array
(
    [day] => 42
    [hour] => -5
    [minutes] => 3
)
Run Code Online (Sandbox Code Playgroud)


Mic*_*nio 16

对于这种情况你应该使用正则表达式

<?php
 $time = "1d2h3m";
 if(preg_match("/([0-9]+)d([0-9]+)h([0-9]+)m/i",$time,$regx_time)){
    $day = (int) $regx_time[1];
    $hour = (int) $regx_time[2];
    $minute = (int) $regx_time[3];
    var_dump($day);
 }
?>
Run Code Online (Sandbox Code Playgroud)

说明:
[0-9]:匹配0到9之间的任何数字
[0-9] +:表示匹配数字至少一个字符
([0-9] +):表示,匹配至少一个字符的数字并捕获结果
/........../i:为您设置的正则表达式设置不区分大小写

正则表达式更好地成为词法分析器和词法分析字符串.学习正则表达式很好.几乎所有编程语言都使用正则表达式


Hal*_*nis 12

可自定义的功能,最重要的是,如果输入未正确形成,您可以捕获异常

/**
  * @param $inputs string : date time on this format 1d2h3m
  * @return array on this format                 "day"      => 1,
  *                                              "hour"     => 2,
  *                                              "minutes"  => 3        
  * @throws Exception
  *
  */
function dateTimeConverter($inputs) {
    // here you can customize how the function interprets input data and how it should return the result
    // example : you can add "y"    => "year"
    //                       "s"    => "seconds"
    //                       "u"    => "microsecond"
    // key, can be also a string
    // example                "us"  => "microsecond"
    $dateTimeIndex  = array("d" => "day",
                               "h" => "hour",
                               "m" => "minutes");

    $pattern        = "#(([0-9]+)([a-z]+))#";
    $r              = preg_match_all($pattern, $inputs, $matches);
    if ($r === FALSE) {
        throw new Exception("can not parse input data");
    }
    if (count($matches) != 4) {
        throw new Exception("something wrong with input data");
    }
    $datei      = $matches[2]; // contains number
    $dates      = $matches[3]; // contains char or string
    $result    = array();
    for ($i=0 ; $i<count ($dates) ; $i++) {
        if(!array_key_exists($dates[$i], $dateTimeIndex)) {
            throw new Exception ("dateTimeIndex is not configured properly, please add this index : [" . $dates[$i] . "]");
        }
        $result[$dateTimeIndex[$dates[$i]]] = (int)$datei[$i];
    }
    return $result;
}
Run Code Online (Sandbox Code Playgroud)


Scu*_*zzy 5

另一种正则表达式解决方案

$subject = '1d2h3m';
if(preg_match('/(?P<day>\d+)d(?P<hour>\d+)h(?P<minute>\d+)m/',$subject,$matches))
{
  $result = array_map('intval',array_intersect_key($matches,array_flip(array_filter(array_keys($matches),'is_string'))));
  var_dump($result);
}
Run Code Online (Sandbox Code Playgroud)

返回

array (size=3)
  'day' => int 1
  'hour' => int 2
  'minute' => int 3
Run Code Online (Sandbox Code Playgroud)


Man*_*ndi 5

使用这个简单的实现与字符串替换和数组结合.

<?php
   $time = "1d2h3m";
   $time=str_replace(array("d","h","m")," " ,$time);
   $time=array_combine(array("day","hour","minute"),explode(" ",$time,3));

   print_r($time);
?>
Run Code Online (Sandbox Code Playgroud)