Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the cross-platform regex to replace a line ending?

Tags:

regex

php

I've got a string like "foo\nbar", but depending on platform, that could become "foo\n\rbar", or whatever. I want to replace new lines with ", ". Is there a nice (php) regex that'll do that for me?

like image 891
sprugman Avatar asked Jan 29 '10 23:01

sprugman


People also ask

How do you substitute in regex?

To perform a substitution, you use the Replace method of the Regex class, instead of the Match method that we've seen in earlier articles. This method is similar to Match, except that it includes an extra string parameter to receive the replacement value.

How do you break a line in regex?

If you want to indicate a line break when you construct your RegEx, use the sequence “\r\n”. Whether or not you will have line breaks in your expression depends on what you are trying to match. Line breaks can be useful “anchors” that define where some pattern occurs in relation to the beginning or end of a line.

Which regex option matches any character including a new line?

Multiline option, it matches either the newline character ( \n ) or the end of the input string.

What is$ 1 in regex?

The $ number language element includes the last substring matched by the number capturing group in the replacement string, where number is the index of the capturing group. For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.


1 Answers

Try the regular expression (?:\r\n|[\r\n]):

preg_replace('/(?:\r\n|[\r\n])/', ', ', $str)
like image 108
Gumbo Avatar answered Sep 29 '22 03:09

Gumbo