减负爆炸整数范围

时间:2019-04-28 11:46:24

标签: php

是否有比使用爆炸功能更好的解决方案,使第一个和第二个值被带负值的“-”爆炸,并检查有多少个负号?

$list = [
    '10-20',
    '12-14',
    '-5-10',
    '-10--2'
];

我想收到:

$first = 10; $second = 20;
$first = 12; $second = 14;
$first = -5; $second = 10;
$first = -10; $second = -2;

1 个答案:

答案 0 :(得分:3)

您可以使用preg_split来爆炸您的字符串,搜索以数字开头的-

foreach ($list as $item) {
    list($first, $second) = preg_split('/(?<=\d)-/', $item);
    echo "\$first = $first, \$second = $second\n";
}

输出:

$first = 10, $second = 20 
$first = 12, $second = 14 
$first = -5, $second = 10 
$first = -10, $second = -2

Demo on 3v4l.org