How to replace new line - php

$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);

Related

removing \n from a string retrieved from DB

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

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.

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 :)

Replace newline from MySQL TEXT field to parse w/ JSON

"replace newline" seems to be a question asked here and there like hundred times already. But however, i haven't found any working solution for myself yet.
I have a textarea that i use to save data into DB. Then using AJAX I want to get data from the DB in the backend that is in TEXT field and to pass it to frontend using JSON. But pasing JSON returns an error, as new lines from DB are not valid JSON syntax, I guess i should use \n instead...
But how do i replace newlinew from DB with \n?
I've tried this
$t = str_replace('<br />', '\n', nl2br($t));
and this
$t = preg_replace("/\r\n|\n\r|\r|\n/", "\n", $t);
and using CHAR(13) and CHAR(10), and still I get an error
the new line in textarea is equivalent to, i guess
$t = 'text with a
newline';
it gives the same error. And in notepad i clearly see that it is crlf
You need to escape all the characters that have a special meaning in JSON, not only line feeds. And you also need to convert to UTF-8.
There's no need to reinvent the wheel, json_encode() can do everything for you.
Prfff... >_< silly me
I've lost another slash before replacing with \n
$t = preg_replace("/\r\n|\n\r|\r|\n/", "\\n", $t);

html source encode

when I view source on my php page I get " for a quote. But instead, I would like " to be used in the source code. I have no control over manually replacing it so Im wondering if there is a function to do such a thing.
If you have access to the PHP and want to change all html special characters to their rightful variations use:
print htmlspecialchars_decode($string);
You could do this very simply using str_replace.
$string = str_replace('"', '"', $string);
However, as Levi said, why not just leave it this way? It should have no effect on the display.

Categories