如何在PHP中将数字与数字分开
问题描述:
I have string as following:
$str = "Q1-Q4,A3-A6,S9-S11";
Can someone tell me how to split the above text in PHP so that I get following as output:
Q1,Q2,Q3,Q4,A3,A4,A5,A6,S9,S10,S11
我的字符串如下: p>
$ str =“ Q1-Q4,A3-A6,S9-S11“;
code> pre>
有人能告诉我如何在PHP中拆分上述文本,以便我得到以下输出: p>
Q1,Q2,Q3,Q4,A3,A4,A5,A6,S9,S10,S11 p>
blockquote>
答
This should get you going. This separates the sequences, adds in extra items and returns all of this as an array you can conveniently use.
$str = "Q1-Q4,A3-A6,S9-S11";
$ranges = explode (',', $str);
$output = [];
foreach ($ranges as $range) {
$items = explode ('-', $range );
$arr = [];
$fillin = [];
$letter = preg_replace('/[^A-Z]/', '', $items[0]);
$first = preg_replace('/[^0-9]/', '', $items[0]);
$last = preg_replace('/[^0-9]/', '', end($items));
for($i = $first; $i-1 < $last; $i++) {
$fillin[] = $letter . $i;
}
$output[] = $fillin;
}
var_dump( $output );
exit;
答
You will want to split the string using a regular expression, preg_split will be the ideal function to use in this case:
$str = "Q1-Q4,A3-A6,S9-S11";
$temp = preg_split('/[-,]/',$str);
print_r($temp);
Hope this helps,