Search code examples
phpregexregex-group

Way to match *all* newline-type character sequences in a text file


I'm looking for a way to obtain all sequences of newline-like characters found in a string. I'm trying to use preg_match() as follows:

preg_match('/^[^\r\n]*(?:([\r\n]+)|[^\r\n]*)+$/', $input_text, $matches);

But I only appear to be getting the last such match. I feel like the solution probably involves the use of \G, but when I attempt to introduce it, the match fails entirely. I don't think I'm understanding how to use it correctly or where it should go.

I realize my pattern will match multiple newlines in sequence (i.e. blank lines lead to multiple newlines in a single match). This is what I want.

For example, for the string:

"ABC\nDEF\r\n\rGHI\n\n\r\n",

I would like to get:

[ "\n", "\r\n\r", "\n\n\r\n" ]

Thanks for any assistance.


Solution

  • Use

    preg_match_all('/\R+/u', "ABC\nDEF\r\n\rGHI\n\n\r\n", $matches);
    

    It returns all line ending sequences because \R+ matches one or more line ending sequences.