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);