0

How to do this in $string:

preg_replace("~\r\n~i","",$string)

But not between <script> </script>

CSᵠ
  • 10,049
  • 9
  • 41
  • 64
  • 2
    [By using a DOM parser](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) and applying the replacement only to non-`script` nodes. – Martin Ender Aug 03 '13 at 13:42
  • why would it matter if you replace line-feeds in the script? In general it shouldn't matter; javascript code is commonly minified by removing white space. – Spudley Aug 03 '13 at 14:02
  • @Spudley some people like to omit semicolons in JS. – Martin Ender Aug 03 '13 at 15:14
  • @m.buettner - they shouldn't, but that's a whole different discussion. ;-) – Spudley Aug 03 '13 at 16:07

1 Answers1

2

The trick is to take the <script> tag into a subpattern and insert it again. In this way we safe it from being touched.

preg_replace('~\r\n|(<script>.*?</script>)~s', '$1', $str);

The ~s modifier is needed that . matches newlines too.

Credits for the simplified pattern goes to @m.buettner from the comments.

Martin Ender
  • 43,427
  • 11
  • 90
  • 130
flori
  • 14,339
  • 4
  • 56
  • 63
  • @PetrNovotný What do you mean? Does this second version work for you? – flori Aug 03 '13 at 14:11
  • 1
    Note that this does not help if the input starts with a script tag on the first line. I'd rather do `\r\n|()` and replace that with `$1`. This will skip over any script tags and remove all other line breaks it finds. – Martin Ender Aug 03 '13 at 22:21
  • @m.buettner Your pattern is simpler and works better. I hope it is okay if I adopt in in the answer. – flori Aug 04 '13 at 01:14
  • What if there's a `\n` that's not preceded by `\r`? Or `\r` not followed by `\n`? All three forms are valid. Since you're deleting them all, I recommend you use `[\r\n]+` instead of `\r\n`. – Alan Moore Aug 04 '13 at 02:07
  • @AlanMoore unless you know your input contains only Windows line breaks (in which case your approach still wouldn't harm, of course). – Martin Ender Aug 04 '13 at 10:49