removing \n from a string retrieved from DB - php

I have tried quite a few things so far with no luck:
I am using TinyMCE, which I run through mysql_real_escape_string() then add to database.
heres an example of the string thats stored in the DB:
<p>It would be nice to be able to put this in 2 categories....</p>\n<p>something to think about.</p>
I retrieve the data then I get problems. I can't get rid of the \n
$string = the database entry listed above
$string = substr($item['body'], 0, 120). "...";
$item['bodysum'] = nl2br(stripslashes(str_replace("\n", "<br />", $string)));
Here is a pic of the output.
I just want it to be normal HTML. If possible I'd like to convert it all to one line as well instead of making the section larger. Its supposed to be a summary of what someone posts, so having it make the summary area larger for 1 word then a new line doesn't make sense!

Is that "\n" a literal "\" followed by "n"? If that's the case, then try:
$item['bodysum'] = nl2br(str_replace("\\n", "<br />", $string));

Try first strip_slashes than nl2br
$item['bodysum'] = nl2br(stripslashes($string));

Try this
$text = '<p>It would be nice to be able to put this in 2 categories....</p>\n<p>something to think about.</p>';
echo preg_replace('#(\\\r|\\\r\\\n|\\\n)#', '<br/>', $text);
EXAMPLE HERE

Related

How to remove \n\n characters, line break from php string

I am trying to remove these \n\n characters that appear in my string when I post a form.
My code is;
$text = $textdb['columnname'];
echo trim(preg_replace('/\s\s+/', ' ', $text));
But it doesn't work. I have tried literally every example here and still nothing works. Am I suppose to do something prior to this? Does this work with a certain version of php? Am using 5.6 by the way. Thanks.
Just use nl2br
Example:
$text = nl2br("hey\n neighbor");
would print
hey
neighbor

How to replace new line

$t = '"Confidence isn\'t gained over time and practice. Confidence is gained when you realize you choose your own path, you choose to fall, you choose not to fall.
If you are afraid to fall you fall because you are afraid. Everything is choice." - Daniel ILabaca';
$order = array("\r\n", "\n", "\r");
$text = str_replace($order, '<br/>', $t);
But in the database is still the new line.
Before inserting I do htmlspecialchars(addslashes(trim($text)))
Why don't you have a go with the nl2br() function? Try this:
$text = nl2br($t);
Instead of the following two rows that is:
$order = array("\r\n", "\n", "\r");
$text = str_replace($order, '<br/>', $t);
While saving data in DB it only needs to be escaped to prevent SQL injection. No need to execute htmlspecialchars, nl2br, addslashes etc. You save the user data as it is. But make sure its safe. You should use htmlentities, nl2br, addslashes etc functions while displaying this data at the presentation layer.
If you don't want any linebreaks at all and don't want to have them converted to HTML <br > have a look at this here: Remove all the line breaks from the html source
You should use PHP built-in method nl2br()
nl2br — Inserts HTML line breaks before all newlines in a string
Example
<?php
echo nl2br("Welcome\r\nThis is my HTML document", false);
?>
Output
Welcome<br>
This is my HTML document
Instead of the $order and str_replace bits, simply try $text = nl2br($t);

remove \n from paragraph

I have a jquery editable div that when you click on it you can edit the text. The problem is that when the data is called from the db and placed into the paragraph I keep getting a \n for every space. How can I replace the \n with an actual new line.
I tried nl2br(), but that's not very convenient for my users since they then have to play with the <br /> when they want to edit the paragraph.
Any thoughts?
What about:
str_replace("\\n", "", $str); // see if this gets rid of them
Then this should work to put actual newlines in there:
str_replace("\\n", "\n", $str); // should replace with actual newline
try:-
$strippedText = str_replace(chr(10), '', $textFromDB);
or
$strippedText = str_replace(chr(10), '<br/>', $textFromDB);
Does this work? (Working on the possiblity that the newlines are already escaped).
$strippedText = str_replace('\\n', ' ', $textFromDB);
Are you using a ready made solution or making your own? I use http://aloha-editor.org/ for stuff like this and it's mostly problem free.
Have you tried str_replace?
$myTextFromDB = str_replace('\n', PHP_EOL, $myTextFromDB);
Ok, I think this is different enough that I should do a separate answer for it.
Are you saying a literal "slash n" shows up on the page? Or are you saying that your newlines show up as spaces?
If it's the latter, then there's no way around that. HTML will show newlines only as a space - you have to convert to br tags to break the line if it's not in a textarea context. But you can always convert them back to newlines when you pop that textarea up for your user and this should work well for people.

PHP str_replace not working correctly

I'm using str_replace and it's not working correctly.
I have a text area, which input is sent with a form. When the data is received by the server, I want to change the new lines to ",".
$teams = $_GET["teams"];
$teams = str_replace("\n",",",$teams);
echo $teams;
Strangely, I receive the following result
Chelsea
,real
,Barcelona
instead of Chealsea,real,Barcelona.
What's wrong?
To expand on Waage's response, you could use an array to replace both sets of characters
$teams = str_replace(array("\r\n", "\n"),",",$teams);
echo $teams;
This should handle both items properly, as a single \n is valid and would not get caught if you were just replacing \r\n
Try replacing "\r\n" instead of just "\n"
I would trim the text and replace all consecutive CR/LF characters with a comma:
$text = preg_replace('/[\r\n]+/', ',', trim($text))
I had the same issue but found a different answer so thought I would share in case it helps someone.
The problem I had was that I wanted to replace \n with <br/> for printing in HTML. The simple change I had to make was to escape the backslash in str_replace("\n","<br>",($text)) like this:
str_replace("\\n","<br>",($text))

nl2br not working for me

I can't get nl2br function to work after fetching data from my database:
$result = mysql_query("SELECT comments..etc.etc..");
while ($row = mysql_fetch_array($result))
{
echo nl2br($row["comments"]);
}
In database row comments:
\r\nThanks,\r\n
OUTPUT:
Same as in DB:
\r\nThanks,\r\n
If I simply test this out like so it works fine:
<?php
$mystring = "\r\nThanks,\r\n";
echo nl2br($mystring);
?>
OUTPUT:
converts \r \n to <br />
try this:
echo preg_replace('/\v+|\\\r\\\n/Ui','<br/>',$row["comments"]);
I know this is an old post but if like me you are have stumbled across this issue and the above didn't work for you, this solution may help you instead:
echo nl2br(stripslashes($row["comments"]));
or (they are not the same function, note the additional "c" after strip)
echo nl2br(stripcslashes($row["comments"]));
See original thread that helped me: nl2br() not working when displaying SQL results
Most likely you are doing escaping twice, when adding your data into DB.
Check your code that adds data to DB and remove unnecessary escaping.
Most likely it's some senseless "universal sanitization" function.
Well it's easy.
Let's take a quote, not a newline to demonstrate. The behavior the same.
Slashes being stripped then data goes to database.
Thus, in the normal case:
source: It's
after escaping: It\'s
by the query execution slash being stripped and
both in the database and back It's
in double escaping case:
source: It's
after escaping: It\'s
after second escaping: It\\\'s
by the query execution slash being stripped and
both in the database and back It\'s
we have our data spoiled.
Just make yourself understand that escaping i not something magical that makes your data "safe" (and, therefore can be done many times, as you probably think). It's just adding a backslash to certain symbols.
My guess is that the slashes in your DB are literal slashes (followed by n or r), not newlines. Can you find a way to store literal newlines in your database?
Following solution will work for both windows as well as for linux/unix machine
str_replace(array("\\r\\n", "\\r", "\\n"), "<br />", "string");
Make sure that you are not to using strings from file and/or set in single apostrophe. Because string is treated literally, and nl2br will not work.
NL2BR will work with double apostrophe.
Building on what Christian is saying, why don't you trying replacing the literal '\r\n' with "\r\n"?
Data you have stored is allready added the slashes.
You have to use stripslashes() first then str_replace()
stripslashes(str_replace('\r\n','<br/>',$row["comments"]))
For some reason this didn't work for me...
echo nl2br(stripcslashes($row["comments"]));
But this did...
$comments = stripcslashes($row["comments"]);
$commentsWithBreaks = nl2br($comments);
echo $commentsWithBreaks;
Not working for me either. I just did the following:
$mensaje = str_replace("
", "<br/>", $mensaje);
I was able to replace newline with <br> using this code :
str_replace(array("\r\n", "\r", "\n"), "<br>", "input");
(windows machine)
This could be a solution, at least it was for me.
$message = str_replace("\\r\\n", "<br>", $message);
It is possible that you are getting a string in which the slashes are escaped (i.e. \\) and nl2br works with \n\r not \\n\\r
Once you understand this, the solution is easy :)

Categories