I’ve gone over other questions from stack overflow with similar ideas but none seem to resemble closely enough what I’m trying to do.
Seems simple, but I’m in a pickle.
I’m trying to replace multiple occurrences of a line break (\n) with only one line break, so people won’t be able to submit more than one line break at a time.
Here’s what I’ve tried.
$text = "Foo\n\n\nbar!\n\nfoobar!";
$text = preg_replace("#\n+#", "\n", $text);
echo $text;
The expected returned statement would be:
Foo\nbar!\nfoobar!
But no cigar!
I tried several but none seemed to work.
What am I doing wrong?
Thanks!
If you’re only interested in the solution, skip to the last line.
Here’s what ended up happening. I had a
divtag in html that contained certain information.When a user hits a button, a JS code runs that converts that
divto aninputtextbox, and sets the value of that textbox as the html of the original div – while replacing all occurrences of<br>with\nto create real line breaks.The form then got submitted via ajax to the server.
When I tried to replace the line breaks in PHP, none of the above suggestions helped, for the simple reason that it wasn’t (curiously enough) a “real” linebreak character. What got submitted to the server was the literal
\n.You’d think escaping the backslash in
\n, as suggested by ghostdog74 would solve the problem but it did not. I tried escaping it several different ways but nothing seemed to help.I ended up referencing some old regex material and found that:
Following that, here’s the piece of code that solved my problem:
Thank you everybody for all your help! +1 for all 🙂