将可读php字符串插入到中以分离变量


Sprit readable php string in to separate variables

我有一个可读的时间字符串,它是这样的,我想把它作为$day,$hours,$minutes,$seconds 3天3小时3分47秒来分隔变量

这是我迄今为止写的代码

<?php
$all_time_string="test 100 years 40 nummonths 60 days 1000 hours 3 minutes 57.9 seconds";
$get_years=explode("years", $all_time_string,2);
if($get_years[1]!=null) {
    $get_nomonths=explode("nummonths",$get_years[1],2);
} else {
    $get_nomonths=explode("nummonths",$get_years[0],2);
}
if($get_nomonths[1]!=null) {
    $no_of_days=explode("days", $get_nomonths[1],2);
} else {
    $no_of_days=explode("days", $get_nomonths[0],2);
}
if($no_of_days[1]!=null) {
    $get_hours=explode("hours", $no_of_days[1],2);
} else {
    $get_hours=explode("hours", $no_of_days[0],2);
}
if($get_hours[1]!=null) {
    $get_minutes=explode("minutes", $get_hours[1],2);
} else {
    $get_minutes=explode("minutes", $get_hours[0],2);
}
if($get_minutes[1]!=null) {
    $get_seconds=explode("seconds", $get_minutes[1],2);
} else {
    $get_seconds=explode("seconds", $get_minutes[0],2);
}
echo $get_years[0];
echo $get_nomonths[0];
echo $no_of_days[0];
echo $get_hours[0];
echo $get_minutes[0];
echo $get_seconds[0];
echo "<br>";
?>

您可以使用正则表达式来拆分字符串:

$pattern = "([0-9]+)('s+)years('s+)([0-9]+)('s+)nummonths('s+)([0-9]+)('s+)days('s+)([0-9]+)('s+)hours('s+)([0-9]+)('s+)minutes('s+)([0-9'.]+)('s+)seconds";
$all_time_string="test 100 years 40 nummonths 60 days 1000 hours 3 minutes 57.9 seconds";
$matches = array();
preg_match("/".$pattern."/i", $all_time_string, $matches);
$myArray = array(
    "years" => $matches[1],
    "months" => $matches[4],
    "days" => $matches[7],
    "hours" => $matches[10],
    "minutes" => $matches[13],
    "seconds" => $matches[16],

);
var_dump($myArray);

然后输出为:

array
    'years' => string '100' (length=3)
    'months' => string '40' (length=2)
    'days' => string '60' (length=2)
    'hours' => string '1000' (length=4)
    'minutes' => string '3' (length=1)
    'seconds' => string '57.9' (length=4)