通过Regex将字符串解析为具有新行链的数组,而不使用PHP中的任何删除

通过Regex将字符串解析为具有新行链的数组,而不使用PHP中的任何删除

问题描述:

I need to parse this string:

$str = "


ABC

DEF
GHI


JKL" ;

into this array:

$arr = [
    "


",
    "ABC
",
    "
",
    "DEF
",
    "GHI
",
    "

",
    "JKL"
] ;

I tried many combinations, but no luck:

$arr = preg_match_all("/[^
]+[
]+/",$str,$out) ;

What Regex can handle that?

我需要解析这个字符串: p>

  $ str =  “
 
 
ABC 
 
DEF 
GHI 
 
 
JKL”; 
  code>  pre> 
 
 

进入此数组: p>

  $ arr = [
“
 
 
”,
“ABC 
”,
“
”,
“DEF 
”,
“GHI 
  “,
”
 
“,
”JKL“
]; 
  code>  pre> 
 
 

我尝试了很多组合,但没有运气: p>

  $ arr = preg_match_all(“/ [^ 
] + [
] + /”,$ str,$ out); 
  code>  pre> 
  
 

Regex可以处理什么? p> div>

This pattern does the job:

preg_match_all('~
+|.+
?~', $str, $matches);

demo

As an aside, preg_match_all returns the number of matches or false, the matches are stored in the third parameter.