doulei1965 2017-08-11 20:41
浏览 69
已采纳

通过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?

  • 写回答

1条回答 默认 最新

  • douju1365 2017-08-11 20:47
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?