没有连续的空间RegEx Group PHP

时间:2015-11-18 02:14:26

标签: php regex preg-match preg-match-all

^([A-Za-z0-9 ]){8,12}

如何将其转换为可以在任何地方连续但不连续的空间?

Id est:

A L L 0 W E D

N O T  A L L 0 W E D # Note two spaces between `not` and `allowed`

1 个答案:

答案 0 :(得分:2)

您可以使用lookahead / behind技术,如下所示:'/^([A-Za-z0-9]| (?! )){8,12}/'。这意味着我们期望A-Z,a-z和0-9 OR空间,但不是空格。看看结果:

$strs = array(
    '12345678',
    'A L L 0 W E D',
    'N O T  A L L 0 W E D' # Note two spaces between `not` and `allowed`
);

$preg = '/^([A-Za-z0-9]| (?! )){8,12}/';

foreach ($strs as $str) {
    var_dump(preg_match($preg, $str));
}

return;

它将返回:

int(1)
int(1)
int(0)