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?
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.
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.
Multiline option, it matches either the newline character ( \n ) or the end of the input string.
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.
Try the regular expression (?:\r\n|[\r\n])
:
preg_replace('/(?:\r\n|[\r\n])/', ', ', $str)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With