PHP 正则表达式匹配四个空格,但不匹配五个空格


PHP Regex match four spaces but not five

    This is a line indented with four spaces
        another one with eight spaces
    now the last with four

这是我的字符串,我想在四个空格上preg_split,而不是更多,我正在使用,

preg_split('/^    /m', $str)

结果:

array(4) {
  [0]=>
  string(0) ""
  [1]=>
  string(41) "This is a line indented with four spaces
"
  [2]=>
  string(34) "    another one with eight spaces
"
  [3]=>
  string(22) "now the last with four"
}

我希望具有四个以上空格的行成为第一次拆分的一部分,我很难理解非捕获或负前瞻正则表达式。

要在 4 个空间而不是第 5 个空间上拆分,您可以使用以下负面展望:

$arr = preg_split('/^ {4}(?! )/m', $str);

其中(?! )是负前瞻,如果旁边有第 5 个空格,则在开始时将无法匹配 4 个空格。


编辑要避免拆分数组中的空值,请使用:

 $arr = preg_split('/^ {4}(?! )/m', $str, -1, PREG_SPLIT_NO_EMPTY);