0

I want to replace linebreaks with ' ' in PHP. Somehow I can't get it to work on this json encoded string [[0,"Hello World"],[1,"s\n"]] with $x = preg_replace('/\r\n|\r|\n\r|\n/m', ' ', $x);.

I'm out of ideas. And i know that the php code works with none-json encoded strings. Any ideas to fix this problem

Forgot this:

When I input the string as $xthe function or php code returns the same string. Instead of replacing \n with ' '.

I have also tried all relevant problems in Stackoverflow. none of them successful

2
  • What doesn't work about it? Provide "before" and "after" strings for clarity. Commented Sep 5, 2011 at 17:49
  • When I input the string as $xthe function or php code returns the same string. Commented Sep 5, 2011 at 17:52

1 Answer 1

1

preg_replace will try to parse the '\n' as an actual newline character, so you need some more escaping in there.

$x = preg_replace('/\\\r\\\n|\\\r|\\\n\\\r|\\\n/m', ' ', $x);

This is all kind of ugly though. Is there a reason you can't do a replace in the actual decoded strings instead?

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @Logan it worked! I dont want to replace in the client side though
I seriously doubt that that works and fixes your problem. I tried the pattern from your question, and that works; this escaped one (though escaping isn't necessary since the pattern is between single quotes which does nothing with \n or \r) doesn't work.
I'll be honest, I kind of expected his sample code to work too, but when I tried it on my computer, it didn't. I tried it with the extra escaping and it works. I'm using Ubuntu 10.10 and PHP 5.3.3, you?
@Logan I've tested on the same system.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.