2

我正在寻找在 php 中创建一个从以下格式获取数据的正则表达式:

"1,2,3;7,1,3;1" returns an $matches array with "(1,2,3,7,1,3,1)"

"1" returns an $matches with "(1)"

"1;1;3;5;7;10;999" returns an $matches array with "(1,1,3,5,7,10,999)"

"1,1,1;2,5;3,4" doesn't pass since numbers are repeating within semicolon boundaries

"2,3,4;5,;" doesn't pass since it doesn't satisfy the format.

(示例中的引号是为了使它们更易于阅读;它们不应出现在实际结果中。)

格式是用逗号或分号分隔的数字,在分号内它们不会相互重复。它不应该接受任何其他格式。

我试过/(^(\d{1,3})$)|(([0-9]+)([,|;]{1}[0-9]+)+)/了,但没有用。我也试过/[0-9]+([,|;]{1}[0-9]+)+/,但也没有用。当我得到 $matches 数组时,它没有我需要的值,如上所述。

我在PHP 5.2中这样做。谢谢。

4

2 回答 2

2

这个特殊的问题有太多的逻辑,正则表达式不实用;这就是您可以使用常规代码解决它的方法:

// reduction function - keeps merging comma separated arguments
// until there's a duplicate or invalid item
function join_unique(&$result, $item)
{
    if ($result === false) {
        return false;
    }

    $items = explode(',', $item);
    $numbers = array_filter($items, 'is_numeric');

    if (count($items) != count($numbers)) {
        return false;
    }

    $unique = array_unique($numbers);

    if (count($unique) != count($numbers)) {
        return false;
    }

    return array_merge($result, $numbers);
}

// main function - parse a string of comma / semi-colon separated values
function parse_nrs($str)
{
    return array_reduce(explode(';', $str), 'join_unique', array());
}

var_dump(parse_nrs('1,2,3;7,1,3;1'));
var_dump(parse_nrs('1'));
var_dump(parse_nrs('1;1;3;5;7;10;999'));
var_dump(parse_nrs('1,1,1;2,5;3,4'));
var_dump(parse_nrs('2,3,4;5,;'));

输出:

array(7) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "7"
  [4]=>
  string(1) "1"
  [5]=>
  string(1) "3"
  [6]=>
  string(1) "1"
}
array(1) {
  [0]=>
  string(1) "1"
}
array(7) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "1"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "5"
  [4]=>
  string(1) "7"
  [5]=>
  string(2) "10"
  [6]=>
  string(3) "999"
}
bool(false)
bool(false)

也可以看看:array_reduce() array_unique()

于 2013-04-24T16:59:46.177 回答
1

一步完成是不可能的。首先,您需要检查在分号边界内重复数字的要求,然后如果通过检查,则拆分字符串。

例如:

if (!preg_match('/\b(\d+),[^;]*\b\1\b/', $string)) {
    $matches = preg_split('/[,;]/', $string);
} else {
    $matches = NULL;
}

ideone:http: //ideone.com/Y8xf1N

于 2013-04-24T16:56:51.153 回答