我有一个喜欢的字符串
(1-1, 1-2, 1-3, 2-7, 2-8, 2-9, 3-13, 3-14, 3-15, 4-19, 4-20, 4-22, 4-23, 4-24)
这里第一个数字表示表格,第二个数字表示另一个数字,我们需要将第一个数字合并为一个(意思是,任何数字都不应显示多次)。
谁能帮我分成2个不同的字符串?
例如
$main-string=(1-1, 1-2, 1-3, 2-7, 2-8, 2-9, 3-13, 3-14, 3-15, 4-19, 4-20, 4-22, 4-23, 4-24);
需要像下面这样的输出
$number-1= 1,2,3,4;
$number-2= 1,2,3,7,8,9,13,14,15,19,20,22,23,24;
答案 0 :(得分:2)
您可以使用 preg_match_all
查找字符串中的所有 digits-digits
值;然后简单地将 array_unique
应用于第一个匹配项以仅获取该数组的唯一值:
$string='(1-1, 1-2, 1-3, 2-7, 2-8, 2-9, 3-13, 3-14, 3-15, 4-19, 4-20, 4-22, 4-23, 4-24)';
preg_match_all('/(\d+)-(\d+)/', $string, $matches);
$tables = array_unique($matches[1]);
$numbers = $matches[2];
print_r($tables);
print_r($numbers);
输出:
Array
(
[0] => 1
[3] => 2
[6] => 3
[9] => 4
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 7
[4] => 8
[5] => 9
[6] => 13
[7] => 14
[8] => 15
[9] => 19
[10] => 20
[11] => 22
[12] => 23
[13] => 24
)
如果您希望答案为逗号分隔的字符串,您可以使用 implode
例如
echo implode(',', $tables);
答案 1 :(得分:0)
<?php
$str = "1-1, 1-2, 1-3, 2-7, 2-8, 2-9,3-13, 3-14,3-15, 4-19, 4-20, 4-22, 4-23, 4-24";
$str = str_replace(' ', '', $str); //remove spaces
$explodeStr = explode (',', $str);
foreach ($explodeStr as $s) {
$a1[] = explode ('-', $s)[0];
$a2[] = explode ('-', $s)[1];
}
var_dump(array_unique($a1));
var_dump(array_unique($a2));
http://sandbox.onlinephpfunctions.com/code/d20ed5b61b719478c2dd550f5b569b1850bb04cb