Skip to content
Advertisement

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('/^[^rn]*(?:([rn]+)|[^rn]*)+$/', $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:

"ABCnDEFrnrGHInnrn",

I would like to get:

[ "n", "rnr", "nnrn" ]

Thanks for any assistance.

Advertisement

Answer

Use

preg_match_all('/R+/u', "ABCnDEFrnrGHInnrn", $matches);

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement