Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php-从包含模式的字符串中提取数字_Php - Fatal编程技术网

php-从包含模式的字符串中提取数字

php-从包含模式的字符串中提取数字,php,Php,我有一根这样的绳子 4-1,4-1,,,1-1,,5-4,2-1, 我需要提取每对中的第一个数字。例如,(4-1、4-1、、1-1、5-4、2-1、) 有人知道我是如何做到这一点的吗 $string = '4-1,4-1,,,1-1,,5-4,2-1,'; preg_match_all('/(\d+)-/', $string, $matches); // search for 1 or more digits that are followed by a hyphen, and return

我有一根这样的绳子

4-1,4-1,,,1-1,,5-4,2-1,
我需要提取每对中的第一个数字。例如,(4-1、4-1、、1-1、5-4、2-1、)

有人知道我是如何做到这一点的吗

$string = '4-1,4-1,,,1-1,,5-4,2-1,';

preg_match_all('/(\d+)-/', $string, $matches);
// search for 1 or more digits that are followed by a hyphen, and return all matches

print_r($matches[1]);
产出:

Array
(
    [0] => 4
    [1] => 4
    [2] => 1
    [3] => 5
    [4] => 2
)

我想我会接受这个答案,因为它的代码更少。谢谢你们两位
$couples = explode(",", $data);
$values = Array();

foreach ($couples as $couple)
{
    if ($couple != "")
    {
        $split = explode("-", $couple);
        $values[] = $split[0];
    }
}