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 :)
Related
I am using PHP/mysqli to read in comments, but various comments in the table have either a single quote or a double quote.
I am storing the comments in a data-attribute. Using the Chrome console, I can see where the quote is throwing the whole code out of whack.
<?php
echo "<td><a href='' class='comment' data-toggle='modal' data-comment='".htmlentities($row[comment])."'>" . $row[partner_name] . "</a></td>";
?>
As you can see in the code above, I tried to use htmlentities. I also tried addslashes and a combination of the two.
Either way, I still can't get the comment to display properly because of the quote inside the mysql table.
Is there another PHP function that I can use to fix this?
Directly above is a screen shot from the Chrome console. Right after the words POTENTIAL 53 there is a single quote that is throwing my code off. All the other orange text is being read as HTML when it's supposed to be part of the comment.
There has to be a way to read the single quote as part of the string.
Pass the flag, ENT_QUOTES, to your htmlentities function. See http://php.net/htmlentities. This will replace quotes with entified quote and prevent it from breaking out of the data-comment attribute.
Well, there are two problems:
You have to encode stuff, especially quotes:
$text = htmlentities($value, ENT_QUOTES);
The title attribute does not work with newlines, so you will have to deal that. Something like this should do the job:
$text = preg_replace('/\r?\n/', '#xA;', $text);
Try escaping the quotes in your data. Something to this affect:
$pattern = "/\"|\'/";
$replace = '\\\"';
$subject = $row[comment];
$rowComment = preg_filter($pattern, $replace, $subject);
*Tip - You can also filter the data before storing it.
Description: echo $rowComment will produce a string with all quotes escaped;
I am trying to display a data into textarea which is fetched from tables that i have submitted via another form. The issue comes up when a new line is entered.
The data getting displayed in the textarea is as
lin1\r\nlin2
it should be like
lin1
lin2
I have tried nl2br but it does not work as expected.
How can i make things optimized. Thanks
This problem can be solved using stripcslashes() when outputting your data.
Please note that the method above is different from stripslashes() which doesn't work in this case.
I tried using nl2br but it wasn't sufficient either.
I hope str_replace saves you.
<?php
$str='lin1\r\nlin2';
$str=str_replace('\r\n','<br>',$str);
echo $str;
OUTPUT:
lin1
lin2
This is a common question and the most common answers are ln2br or str_replace.
However this is just creating unnecessary code.
In reality the problem is pretty much always that you have run the data through a mysql escape function before displaying it. Probably while you were in the process of saving it. Instead, escape the data for saving but display an unescaped version.
<?php echo str_replace('\r\n', "\r\n", $text_with_line_breaks); ?>
See single quotes & double quotes this is a trick.
A perfect solution for newbies.
you overdo quote in insert/update statement
This problem in you case you can solve doing next
<?php
$str = 'lin1\r\nlin2';
$solved_str = str_replace(array("\\r","\\n"), array("\r","\n"), $str);
var_dump($str,$solved_str);
But you need to check insert/update statement on over quotation escape symbols
I would recommend using double quotes for \r\n such as "\r\n". I've never had it work properly with single quotes.
For non- textarea use this function
function escapeNonTextarea($string){
$string=str_replace(array('\n','\r\n','\r'),array("<br>","<br","<br>"),$string);
return $string;
}
For text area use this function
function escapeTextarea($string){
$string=str_replace(array('\n','\r\n','\r'),array("\n","\r\n","\r"),$string);
return $string;
}
call appropriate function and pass argument
For example I want to store the String "That's all". MySQL automatically escapes the ' character. How do I echo that String from the database using php but remove the \ in front of escaped characters like \' ? I would also like to preserve other formatting like new lines and blank spaces.
Have you tried stripslashes(), regarding the linebreaks just use the nl2br() function.
Example:
$yourString = "That\'s all\n folks";
$yourString = stripslashes(nl2br($yourString));
echo $yourString;
Note: \\ double slashes will turn to \ single slashes
You should probably setup your own function, something like:
$yourString = "That\'s all\n folks";
function escapeString($string) {
return stripslashes(nl2br($string));
}
echo escapeString($yourString);
There are also several good examples in the nl2br() docs
Edit 2
The reason your are seeing these is because mysql is escaping line breaks, etc. I am guessing you are using mysql_* functions. You should probably look into mysqli or PDO.
Here is an example:
$yourString = "That's all
folks";
echo mysql_escape_string($yourString);
Outputs:
That\'s all\r\n folks
If you use prepared statements, those characters will not be escaped on insert.
Use stripslashes() to remove slashes if you cannot avoid adding slashes on input.
At first, magic_quotes_gpc escapes the character like ' or ". You can also disable this in your php.ini. But then you should escape the things yourself that no query can get "infected".
Lookup mysql injection for more information.
When the escaped string is been written in your database. The string doesn't contain theses escape charakters and when you output them again. You should see the result as you want it.
Me for myself prefer the method by storing everything without escapes and escape or display things when I output them. You could also easily use an str_replace("\n", "", $text) to prevent newslines are displayed.
Greetings MRu
I'm encoding it like so..
json_encode($array_list, JSON_UNESCAPED_SLASHES)
Ex: \n turns into \\n, \r\n turns into \\r\\n
But, it's still escaping the slashes! What's wrong and how to fix it? Thanks.
I think it is because of single and double quotes, see the examples
$arr = array("\n\r");
echo json_encode($arr,JSON_UNESCAPED_SLASHES); // ["\n\r"]
$arr = array('\n\r');
echo json_encode($arr,JSON_UNESCAPED_SLASHES); //["\\n\\r"]
working example http://codepad.viper-7.com/LvWMhq
If it is a concern when doing any MySQL queries then you can use it like this:
mysql_real_escape_string(json_encode($array))
No need to escape anything in the $array itself before this point, just let mysql_real_escape_string escape the json_encoded string.
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))