如何在PHP中将字符串拆分为3个不同的变量?
问题描述:
I have a bunch of checkboxes with the names like the following:
q1_week1_monday
How can i split these strings into 3 different variables, for example
$quarter = q1;
$week = 1;
$day = monday;
Thanks
我有一堆复选框,其名称如下: p>
q1_week1_monday
code> pre>
如何将这些字符串拆分为3个不同的变量,例如 p>
$ quarter = q1;
$ week = 1;
$ day =星期一;
code> pre>
谢谢 p>
div>
答
Use explode()
to split the string and the list
construct to assign the parts to the variables. Afterwards, get rid of the week-prefix, using regexp.
list ($quarter, $week, $day) = explode("_", "q1_week1_monday")
$week = preg_replace("#week(\d+)#", "$1", $week);
答
Use explode()
to split the string by a delimiter (_
) and then use filter_var()
to get the week number.
$str = 'q1_week1_monday';
$parts = explode('_', $str);
$quarter = $parts[0];
$week = filter_var($parts[1], FILTER_SANITIZE_NUMBER_INT);
$day = $parts[2];
Using list()
construct (a bit more neater):
list($quarter, $week, $day) = explode('_', $str);
$week = filter_var($week, FILTER_SANITIZE_NUMBER_INT);
Note: This assumes the middle part of the string contains only one number.
答
Make use of explode()
and access it as variables like this
$str="q1_week1_monday";
$str=explode('_',$str);
$quarter = $str[0];//q1
$week = intval($str[1]);//1
$day = $str[2];//monday