Sprit читабельная строка php для разделения переменных

0

я hvae readable time string, которая похожа на это, и я хочу, чтобы она разделяла переменные как $day,$hours,$minutes,$seconds 3 Days 3 Hours 3 minutes 47 Seconds

это код, который я написал до сих пор

<?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>";

?>
Теги:

1 ответ

0
Лучший ответ

Вы можете использовать регулярное выражение вместо разделения строки:

$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)
  • 0
    спасибо работает отлично спасибо большое

Ещё вопросы

Сообщество Overcoder
Наверх
Меню