简体   繁体   English

PHP正则表达式:查找字符串中所有连续的数字序列吗?

[英]PHP Regex: find all consecutive number sequences in a string?

Not sure if regular expressions are the right approach for this, but here is what I am looking to achieve... within a string composed of sorted digits such as 234 121 6789 4125 123 I would like to extract all sequences of at least 3 consecutive digits: 不确定正则表达式是否是正确的方法,但是这是我要实现的目标...在由诸如234 121 6789 4125 123之类的排序数字组成的字符串中,我想提取至少3个连续的所有序列位数:

  • 234 234
  • 6789 6789
  • 123 123

Can this be done with regex? 可以用正则表达式完成吗? Otherwise what could be a sensible approach? 否则,什么是明智的方法?

With RegEx, you can use: 使用RegEx,您可以使用:

(123(?:4(?:5(?:6(?:7(?:89?)?)?)?)?)?|234(?:5(?:6(?:7(?:89?)?)?)?)?|345(?:6(?:7(?:89?)?)?)?|456(?:7(?:89?)?)?|567(?:89?)?|6789?|789)

Try here: https://regex101.com/r/Ap8C2D/1 在这里尝试: https : //regex101.com/r/Ap8C2D/1

If you test also with 012…: 如果您也使用012…测试:

(012(?:3(?:4(?:5(?:6(?:7(?:89?)?)?)?)?)?)?|123(?:4(?:5(?:6(?:7(?:89?)?)?)?)?)?|234(?:5(?:6(?:7(?:89?)?)?)?)?|345(?:6(?:7(?:89?)?)?)?|456(?:7(?:89?)?)?|567(?:89?)?|6789?|789)

Test: https://regex101.com/r/zm6I9x/1 测试: https//regex101.com/r/zm6I9x/1

You could use RegEx, but to be honest this would be much simpler to implement a loop and check if the numbers are sequential inside of the loop. 您可以使用RegEx,但是老实说,这将更容易实现循环并检查数字在循环内部是否连续。 Take a look at this example: 看一下这个例子:

$literal = '23412167894125123';

for ($c = 0; $c < strlen($literal) - 2; $c++) {
    if(intval($literal[$c]) + 1 == intval($literal[$c + 1]) &&
       intval($literal[$c]) + 2 == intval($literal[$c + 2])) {
        echo $literal[$c], $literal[$c + 1], $literal[$c + 2], '<br />';
    }
}

Fiddle: Live Demo 小提琴: 现场演示

If the regex looks too complex, this function uses a simple for loop 如果正则表达式看起来太复杂,则此函数使用简单的for循环

function findSeq($string) {

    $seq_started = false;

    $seq = '';

    $list = [];

    for ($i = 1; $i < strlen($string) + 1; $i++) {

        @$curr = $string[$i];
        $prev = $string[$i - 1];
        @$next = $string[$i + 1];

        if ($prev + 1 == $curr) {

            if ($seq_started === false) {

                $seq .= "$prev$curr";

            } else {

                $seq .= $curr;
            }

            $seq_started = true;

            continue;

        }

        if ($seq_started === true) {

            if (strlen($seq) > 2) {

                $list[] = $seq;

            }

            $seq = '';

            $seq_started = false;

        }

    }

    return $list;

}

print_r(findSeq('2341216789412501231456789'));

Output 输出量

Array
(
    [0] => 234
    [1] => 6789
    [2] => 0123
    [3] => 456789
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM