簡體   English   中英

將可讀的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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM