2014-11-11 3 views
0

я hvae читаемой строки времени, которая, как это и я хочу шпринтов его отдельным переменные, как $day,$hours,$minutes,$seconds 3 дня 3 часа 3 минуты 47 секундSprit читаемой PHP строка, чтобы отдельные переменные

этого кода я написал до сей пор

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

это так плохо. вам нужно использовать регулярное выражение. просто дай мне немного времени. – vaso123

ответ

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

спасибо, что он отлично работает благодаря – wordpresrox

Смежные вопросы