繁体   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