用于验证的REGEX模式,检查所有字符串是否为整数并拆分为单个整数

时间:2018-02-27 12:05:11

标签: php regex pcre

我多次尝试制作一个模式,可以验证给定的字符串是自然数并分成单个数字。

..并且对正则表达式缺乏了解,我能想象的最接近的是......

^([1-9])([0-9])*$^([1-9])([0-9])([0-9])*$类似的东西......

它只生成第一个,最后一个,第二个或最后一个第二个分割数。

我想知道解决这个问题我需要知道什么..谢谢

1 个答案:

答案 0 :(得分:2)

您可以使用像

这样的两步解决方案
if (preg_match('~\A\d+\z~', $s)) { // if a string is all digits
    print_r(str_split($s));         // Split it into chars
}

查看PHP demo

一步式正则表达式解决方案:

(?:\G(?!\A)|\A(?=\d+\z))\d

请参阅regex demo

<强>详情

  • (?:\G(?!\A)|\A(?=\d+\z)) - 上一个匹配的结尾(\G(?!\A))或(|)字符串的开头(^),后跟一个或多个数字直到字符串的末尾((?=\d+\z)
  • \d - 数字。

PHP demo

$re = '/(?:\G(?!\A)|\A(?=\d+\z))\d/';
$str = '1234567890';
if (preg_match_all($re, $str, $matches)) {
    print_r($matches[0]);
}

输出:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 0
)