-2

Using preg_replace, I need to define the regex PATTERN to match all instances of the newline sequence \r\n exactly, EXCEPT that occuring at the very end of the text.

preg_replace(PATTERN,'"\r\n"',$text)

How do I specify PATTERN in this case?

Nick
  • 138,499
  • 22
  • 57
  • 95
ptrcao
  • 421
  • 1
  • 5
  • 19

1 Answers1

0

Add a negative lookahead for end-of-line:

preg_replace('/\r\n(?!$)/','"\r\n"',$text)

Demo on 3v4l.org

Note that if you don't have a specific requirement to match \r\n, you can use \R, which will match any newline sequence.

Nick
  • 138,499
  • 22
  • 57
  • 95
  • Oh I see - but in my case, it should strictly be `\r\n` (DOS) and not any other type of newline sequence such as `\n` (Unix) – ptrcao Dec 26 '19 at 12:22
  • @ptrcao ok, ignore the comment about `\R`. See my edit – Nick Dec 26 '19 at 12:23
  • Actually, I found the comment about `\R` quite useful and I've made a note of it - you should probably add that remark back into the answer as an aside, which could be useful fact for future readers – ptrcao Dec 26 '19 at 12:26
  • 1
    @ptrcao good point. I've added it back. :-) – Nick Dec 26 '19 at 12:27
  • Why doesn't entering `\r\n(?!$)` into https://regex101.com/ work to select it? – ptrcao Dec 26 '19 at 12:27
  • @ptrcao I'm not sure how to enter a `\r` character on regex101. I've added a demo on 3v4l instead. – Nick Dec 26 '19 at 12:30
  • I wasn't expecting it to be any different in one regex utility over another - isn't Regex universal? [This SO thread](https://stackoverflow.com/questions/20056306/match-linebreaks-n-or-r-n) might be relevant, however – ptrcao Dec 26 '19 at 12:32
  • @ptrcao the flavour of regex is the same but I don't think it's possible to insert a carriage-return character into the test string in regex101. hence the 3v4l demo – Nick Dec 26 '19 at 12:36