This is probably really stupid, but I try to save content from a texarea into MySQL with PHP. Normally newlines are preserved in the database. But suddenly they are removed.
I use jquery to send the values to PHP with ajax, and then I do this in PHP:
$var = strip_tags( $_POST["var"] );
$db->query("UPDATE table SET var='$var' WHERE id=$id")
Somehow newlines are lost on the way in. If I do nl2br on the var, then they are translated to <br/>, so $var contains newline right up until I run the query.
Update, to add to the strangeness. If I actually run nl2br on $var, and then replace br-tags with newline, before updating the table, all is well, what is going on?!?
This is working just fine:
$var = strip_tags( $_POST["var"] );
$var = nl2br($var);
$var = preg_replace('#<br\s*/?>#i', "\n", $var);
$db->query("UPDATE table SET var='$var' WHERE id=$id");
I've had another look into the Zebra (source code this time), and as mentioned in previous comment this is exactly why newlines get removed. The escape method from Zebra package uses:
http://php.net/manual/en/mysqli.real-escape-string.php
which means the following are removed:
NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.
You could try to add the input in:
<pre></pre>
This will save your input as preformatted text in the database.
Reference: https://www.w3.org/wiki/HTML/Elements/pre
nl2br is a good solution too, use whichever you prefer.
Also make sure you are using the right configuration for your database column. It should be VARCHAR or TEXT.
I think your problem is that newlines get removed before being passed to the server.
You mentioned it's being sent with jQuery so make sure there isn't any client-side processing before being sent to the server.
Related
I have a problem: so I have a data thats coming out of the database and stored in a text area. When the user changes the data in the text area, the content is sent to javascript and via AJAX (POST to a PHP script) the database is updated. This works fine until the user starts adding newlines. Then javascript transforms this into a \n-character and thus it gets stored in the database as \n.
What I want is to have actual newlines in my database and not the \n newline-characters. Is there any way that I can use php to replace the \n with an actual newline (NOT a br)? I have tried altering the database field after the edit with the char(10), but for some reason this is not working in the script except when I do it manually in phpmyadmin?
When editting with a full php request, the newline in a text area is correctly stored as a char(10) in mysql, not as \n.
Anyone got a clue?
Store it as it is but escape first with real_escape_string
real_escape_string converts what is a newline into the 4 character string '\n\r'
$text = $mysqli->real_escape_string($text);
Use [nl2br][1] function to replace /n with newline
Insert line breaks where newlines (\n) occur in the string:
<?php
echo nl2br("One line.\nAnother line.");
?>
The browser output of the code above will be:
One line.
Another line.
I'm having trouble getting data out of the database and echoing out in a HTML page textarea.
This is the code used to get the data into the database:
$_SESSION['content'] = mysqli_real_escape_string($link, strip_tags($_POST['content'],'<a>'));
This simply strips HTML tags except for links and stores in the database. If you look in the database, the line breaks are invisible but there, so i assume they are \n and \r.
If i were to type into a textarea:
This should be a
New line
The database stores this as:
This should be a<br>
New line
When echoed out into a textarea, this is what's displayed:
This should be a \r\n\r\nNew line
I'm sure i'm missing something very simple, any help greatly appreciated.
UPDATE:
If i remove mysqli_real_escape_string, the line breaks are preserved and work perfectly, do I have to sacrifice security for this?
SOLVED:
mysqli_real_escape_string causing the problem, do not echo out a variable which has had this applied. Only use mysqli_real_escape_string when inserting, deleting, etc from a database, not before, definitely not after ;)
Thanks everyone!
Use the correct HTML/CSS.
;-)
The line breaks all work in an HTML pre tag, or in a tag with the CSS white-space property set to:
white-space: pre;
Resources:
http://www.w3schools.com/cssref/pr_text_white-space.asp
http://www.quirksmode.org/css/whitespace.html
Firstly, you shouldn't be using nl2br as this will change your \n's to <br>'s.
You will most likely need to strip the slashes echo stripslashes($_SESSION['content']).
Edit following further comments:
If the data is stored as <br>'s in the database, you can just do str_replace('<br>',"\n",$string); which will convert the <br>'s into \n's
This worked for me:
function br2nl( $input ) {
return preg_replace( '/\<br.*\>/Ui', '', $input );
}
For very long lines, you also need the text to wrap instead of potentially break out of its parent container. To cover this case, but also preserve new lines, use following css:
white-space: pre-wrap;
resource: https://css-tricks.com/almanac/properties/w/whitespace/
The nl2br function is working with that content as a string:
http://codepad.org/M2Jw9KQJ
This leads me to believe that you are not echoing out the content you claim you are.
Are you sure the content in the DB is as you say it is?
Perhaps you need to go the other way round:
function br2nl( $data ) {return preg_replace( "!<br.*>!iU", "\n", $data );}
I've tried about everything to delete some extra \n characters in a web application I'm working with. I was hoping someone has encountered this issue before and knows what can be causing this. All my JS and PHP files are UTF-8 encoded with no BOM.
And yes I've tried things like
In JS:
text.replace(/\n/g,"")
In PHP:
preg_replace("[\n]","",$result);
str_replace("\n","",$result);
and when I try
text.replace(/\n/g,"")
in the firebug console using the same string I get from the server it works but for reason it doesn't work in a JS file.
I'm desperate, picky and this is killing me. Any input is appreciated.
EDIT:
If it helps, I know how to use the replace functions above. I'm able to replace any other string or pattern except \n for some reason.
Answer Explanation:
Some people do and use what works because it just works. If you are like me and for the record I always like to know why what works WORKS!
In my case:
Why this works? str_replace('\n', '', $result)
And this doesn't? str_replace("\n", '', $result)
Looks identical right?
Well it seems that when you enclose a string with a character value like \n in double quotes "\n" it's seen as it's character value NOT as a string. On the other hand if you enclose it in single quotes '\n' it's really seen as the string \n. At least that is what i concluded in my 3 hours headache.
If what I concluded is a setup specific issue OR is erroneous please do let me know or edit.
In php, use str_replace(array('\r','\n'), '', $string).
I guess the problem is you also have \r's in your code (carriage returns, also displayed as newlines).
In javascript, the .replace() method doesn't modify the string. It returns a new modified string, so you need to reference the result.
text = text.replace(/\n/g,"")
Both of the PHP functions you tried return the altered string, they do not alter their arguments:
$result = preg_replace("[\n]","",$result);
$result = str_replace("\n","",$result);
Strangely, using
str_replace(array('\r','\n'), '', $string)
didn't work for me. I can't really work out why either.
In my situation I needed to take output from the a WordPress custom meta field, and then I was placing that formatted as HTML in a javascript array for later use as info windows in a Google Maps instance on my site.
If I did the following:
$stockist_address = $stockist_post_custom['stockist_address'][0];
$stockist_address = apply_filters( 'the_content', $stockist_address);
$stockist_sites_html .= str_replace(array('\r','\n'), '', $stockist_address);
This did not give me a string with the html on a single line. This therefore threw an error on Google Maps.
What I needed to do instead was:
$stockist_address = $stockist_post_custom['stockist_address'][0];
$stockist_address = apply_filters( 'the_content', $stockist_address);
$stockist_sites_html .= trim( preg_replace( '/\s+/', ' ', $stockist_address ) );
This worked like a charm for me.
I believe that usage of \s in regular expressions tabs, line breaks and carriage returns.
I'm using PHP to create some basic HTML. The tags are always the same, but the actual links/titles correspond to PHP variables:
$string = '<p style="..."><strong><i>'.$title[$i].'</i></strong>
<br>';
echo $string;
fwrite($outfile, $string);
The resultant html, both as echoed (when I view the page source) and in the simple txt file I'm writing to, reads as follows:
<p style="..."><a href="http://www.example.com
"><strong><i>Example Title
</i></strong></a></p>
<br>
While this works, it's not exactly what I want. It looks like PHP is adding a line break every time I interrupt the string to insert a variable. Is there a way to prevent this behavior?
Whilst it won't affect your HTML page at all with the line breaks (unless you are using pre or text-wrap: pre), you should be able to call trim() on those variables to remove newlines.
To find out if your variable has a newline at front or back, try this regex
var_dump(preg_match('/^\n|\n$/', $variable));
(I think you have to use single quotes so PHP doesn't turn your \n into a literal newline in the string).
My guess is your variables are to blame. You might try cleaning them up with trim: http://us2.php.net/trim.
The line breaks show up because of multi-byte encoding, I believe. Try:
$newstring = mb_substr($string_w_line_break,[start],[length],'UTF-8');
That worked for me when strange line breaks showed up after parsing html.
"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);