【问题标题】:Split string into 2 different strings base on 2 different symbols根据 2 个不同的符号将字符串拆分为 2 个不同的字符串
【发布时间】:2020-12-22 07:20:13
【问题描述】:

我有一个字符串 Like

(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)

这里第一个数字表示表格,第二个数字表示另一个数字,我们需要将第一个数字合并为一个(意思是,一个数字不应显示超过一次)。

谁能帮我分成两个不同的字符串?

例如

$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;

【问题讨论】:

  • 我已重新格式化,能否请您检查一下我的原始字符串值是否正确?

标签: php arrays string


【解决方案1】:

您可以使用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
)

Demo on 3v4l.org

如果您希望答案为逗号分隔的字符串,您可以使用implode 例如

echo implode(',', $tables);

【讨论】:

    【解决方案2】:
       <?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

    【讨论】:

    • 你可以在', ' 上爆发并消除str_replace 调用。
    • 1-1, 3-13, 没有空格
    • 错过了,抱歉。
    • 我删除了代码中的空格,事实上我们可以使用您的报价
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 2014-09-29
    相关资源
    最近更新 更多