如何搜索彼此相邻的重复数字?

时间:2017-06-17 00:10:36

标签: php regex preg-match numeric capture-group

我试图在PHP中使用preg_match()来为具有此模式的4位数字进行模式匹配:

0033
1155
2277

基本上前2位数字相同,后2位数字相同,但并非所有4位数字都相同。

preg_match()是否使用正确的函数?或者我应该将它们分开并按照这种方式匹配?

2 个答案:

答案 0 :(得分:3)

要在文本中搜索此类数字,您可以使用:

preg_match('~\b(\d)\1(?!\1)(\d)\2\b~', $str, $m)

(或preg_match_all如果你想要所有这些)

细节:

~        # pattern delimiter
\b       # word boundary (to be sure that 1122 isn't a part of 901122)
(\d)     # capture the first digit in group 1
\1       # back-reference to the group 1
(?!\1)   # negative lookahead: check if the reference doesn't follow
(\d)     #
\2       #
\b       # word boundary (to be sure that 1122 isn't a part of 112234)
~        #

如果要检查整个字符串是否为数字,请使用字符串限制锚点代替字边界:

~\A(\d)\1(?!\1)(\d)\2\z~

答案 1 :(得分:1)

您可以使用array_filter之类的内容进行比较回调:

function compare($number) {
    // Compare first 2 numbers
    if (intval($number[0]) !== intval($number[1])) {
        return false;
    }

    // Compare last 2 numbers
    if (intval($number[2]) !== intval($number[3])) {
        return false;
    }

    // Make sure first and last numbers aren't the same
    if (intval($number[0]) === intval($number[3])) {
        return false;
    }

    return true;
}

$data = array_filter($data, 'compare');

你也可以使用闭包来做到这一点:

$data = array_filter($data, function($number) {
    return intval($number[0]) === intval($number[1]) && intval($number[2]) === intval($number[3]) && intval($number[0]) !== intval($number[3]);
});

此处的示例:http://ideone.com/0VwJz8