0

In PHP, I am processing strings between double-quotes, where I have no control over how those strings are generated. Somehow, at some point, newlines appear at the end of some of the strings. It results into something like this:

"This is a value"
"I'm another string!"
"I somehow have a newline at the end
"
"Okay, this is the last one.."

How can I best remove these newlines if I were to iteratively loop through all of these strings?

I can imagine I should use preg_replace, but I don't know what is the best pattern to get rid of the newlines at the end of a quoted string.

Thanks in advance!

Jeroen

Jeroen
  • 325
  • 2
  • 17
  • Should be something like this: `preg_replace('/[\r\n]+"$/, '"', $string);` – Narf Oct 21 '14 at 13:27
  • @Narf: Thanks for your reply! Could you explain this one? Is it like, any newline character, 1 or more, before a double quote? And replace the match with a double quote? – Jeroen Oct 21 '14 at 13:48
  • Basically yes, but technically it replaces with a double quote any number of return carriages and/or newline characters that are followed by a double quote AND that double quote must be the last character in the string. – Narf Oct 21 '14 at 13:52

1 Answers1

2

Something like

  $string = trim(preg_replace('/\s\s+/', ' ', $string));

will do the job

daker
  • 3,243
  • 3
  • 38
  • 52