Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP正则表达式匹配四个空格,但不匹配五个空格_Php_Regex - Fatal编程技术网

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

PHP正则表达式匹配四个空格,但不匹配五个空格,php,regex,Php,Regex,这是我的字符串,我想在四个空格上进行预分割,而不是更多,我正在使用 This is a line indented with four spaces another one with eight spaces now the last with four 结果: preg_split('/^ /m', $str) 我希望包含四个以上空格的行成为第一次拆分的一部分,我很难理解非捕获或负前瞻正则表达式。要在4个空格上拆分,而不是在第5个空格上拆分,可以使用此

这是我的字符串,我想在四个空格上进行预分割,而不是更多,我正在使用

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

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

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

要在4个空格上拆分,而不是在第5个空格上拆分,可以使用此负前瞻:

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"
}
其中,
(?!)
为负前瞻,如果旁边有第5个空格,则在开始时将无法匹配4个空格


编辑:避免分割数组中的空值请使用:

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

顺便说一句,知道如何避免数组开头的空值吗?请检查编辑版本以避免空值。
 $arr = preg_split('/^ {4}(?! )/m', $str, -1, PREG_SPLIT_NO_EMPTY);