I'm using jQuery to output the results of a JSON string created by PHP from a database,
The only problem is that some of the data is on multiple lines... How would I get around this causing an unterminated string literal error in JavaScript?
The following code will get rid of all \r and \n characters.
preg_replace('/[\r\n]+/', "", $stringFromDB)
Escape line endings by replacing "\n" with "\\n" and "\r" with "\\r". You will also want to escape single or double quotes, depending on which you are using to delimit the string.
Related
I have a textarea in my html for user to input some text. I can get it to save into mysql table field with text attribute using php. Before insert into mysql, I will mysql_real_escape_string($data);(for security reason). But when I retrieve it back out from database, I will get
{"bittext":"i
love
mcD"}
With that I will get error:
Error: JSON Parse error: Unterminated string
parse#[native code]
I am not sure how I can reformat it back so that I can parse it to JSON.
Update:
I found out that I did not add json_encode($data) function. Now I can turn
{"bittext":"i
love
mcD"}
into
{"bittext":"i\nlove\nmcD"}
But I am having problem to convert \n to \\n using $data = str_replace(array('\r\n', '\r', '\n'),'\\n', $data);. For some reason \\n is not working. Is there other way to do this?
Update2:
After much of messing around with the code, I finally got it to work:
$je = json_encode($rs,JSON_PRETTY_PRINT);
$nl = array('\r\n', '\r', '\n');
$je = str_replace($nl,'\\n', $je);
My initial issue is when I log it with firephpcore, I can only see \n even after str_replace($nl,'\\n', $je). But as I do more test and found out it actually already work even though it did not display well in console.
From the documentation for mysql_real_escape_string();
mysql_real_escape_string() calls MySQL's library function
mysql_real_escape_string, which prepends backslashes to the following
characters: \x00, \n, \r, \, ', " and \x1a.
Your insert statement will inculde the string '{"bittext":"i \\nlove \\nmcD"}' - notice we are escaping the escape character here, which is what mysql_real_escape_string() does.
Which will insert into your table the string '{"bittext":"i \nlove \nmcD"}' - this is what you should see if you do a select from the mysql client.
Somewhere, either pre-insert, or post-select your code is processing the value and changing '\n', to an actual newline byte, instead of leaving it as the string '\n'.
You could patch this by running;
$data = str_replace(array("\r\n", "\r", "\n"), "\\n", $data);
However, I would recommend you track back through your code to see where in your pipeline escaped strings are getting converted to actuals.
How would I maintain this code so that it doesn't break on a new line. As a result of this string being broken, I am getting a javascript string literal error.
I need to do this on the PHP side.
I've tried str_replace but that doesn't do it. I don't understand why the line is being broken in the first place.
CKEDITOR.instances.article.setData('<p>Test</p>
');
PHP:
$text = '<p>Test</p>';
Javascript string literals cannot have unescaped newlines.
You need to call json_encode() before printing the string to escape newlines and other special characters.
It's a very simple question. I have a textarea. In this textarea are names. Every name in a new row.
Brad Pitt
LMFAO
Green Day
and so on...
I would like to put this names in a database. I tried it with explode() and foreach, but it didn't work. :/
Here is the code:
$kilencedik=array();
$kilencedik=explode('\n',$_POST['9']);
foreach($kilencedik as $nev9) {
$adat9 = pg_escape_string($nev9);
pg_query($kapcsolodas, "INSERT INTO diakok (nev, ev) values ('$adat9', '9')");
}
I'm using postgreSQL with PHP.
It's a ' problem change '\n' to "\n".
Try using explode(PHP_EOL, $_POST['9']);
Using PHP_EOL is more compatilbe across platforms.
If you don;t want to use that you need to at least use double quotes around the \n instead of single quotes. Using double quotes, PHP will interpret that as the newline character whereas using single quote will look for literal \n as string segment to explode on.
In my database I have the following text:
for x in values:
print x
I want to print this code on my HTML page. It is printed by PHP to the HTML file as it is. But when HTML is displayed by a browser I, of course, do not see text in this form. I see the following:
for x in values: print x
I partially solved the problem by nl2br, I also use str_replace(' ',' ',$str). As a result I got:
for x in values:
print x
But I still need to shift print x to the right. I thought that I can solve the problem by str_replace('\t',' ',$str). But I found out that str_replace does not recognize the space before the print as '\t'. This space is also not recognized as just a space. In other words, I do not get any before the print.
Why? And how can the problem be solved?
Quote the text in double quotes, like this
str_replace("\t", ' ', $str);
PHP will interpret special characters in double quoted strings, while in single quoted strings, it will just leave the string, with the only exception of \'.
Old and deprecated answer:
Copy the tab character (" ") from notepad, your databasestring or this post, and add this code:
str_replace(' ',' ',$str);
(this is not four spaces, it is the tab character you copied from notepad)
You need to place \t in double quotes for it to be interpreted as a tab character. Single quoted strings aren't interpreted.
always use double quotes when using \t \n etc
It can be tricky because tabs don't actually have a fixed size and you'd have to calculate tab stops. It can be simpler if you print blank space as-is and instruct the browser to display it. You can use <pre> tags:
<pre>for x in values:
print x</pre>
... or set the white-space CSS property:
div.code{
white-space: pre-wrap
}
(As noted by others, '\t' is different from "\t" in PHP.)
I have a php string with a lot of information to be displayed inside a textarea html element.
I don't have access to that textarea nor to the script (if any) that generates it.
$somestring = 'first line \nSecond line \nThird line.';
$somestring as NOT been "worked" with trim or filter_var. Nothing.
On the textfield, I get the \n printed on the textarea hence, not interpreted.
What can I try in order to have those new lines applied?
Thanks in advance.
Try wrapping $somestring with " (double quotes) instead of ' (single quotes)
\n, \r and other backslash escape characters only works in double quotes and heredoc. In single quotes and nowdoc (the single quote version of heredoc), they are read as literal \n and \r.
Example:
<?php
echo "Hello\nWorld"; // Two lines: 'Hello' and 'World'
echo 'Hello\nWorld'; // One line: literally 'Hello\nWorld'
echo <<<HEREDOC
Hello\nWorld
HEREDOC; // Same as "Hello\nWorld"
echo <<<'NOWDOC'
Hello\nWorld
NOWDOC; // Same as 'Hello\nWorld' - only works in PHP 5.3.0+
Read more about this behaviour in the PHP manual
EDIT:
The reason single and double quotes behave differently is because they are both needed in different situations.
For instance, if you would have a string with a lot of new lines, you would use double quotes:
echo "This\nstring\nhas\na\nlot\nof\nlines\n";
But if you would use a string with a lot of backslashes, such as a file name (on Windows) or a regular expression, you would use single quotes to simplify it and avoid having unexpected problems by forgetting to escape a backslash:
echo "C:\this\will\not\work"; // Prints a tab instead of \t and a newline instead of \n
echo 'C:\this\would\work'; // Prints the expected string
echo '/regular expression/'; // Best way to write a regular expression
$somestring = "first line \nSecond line \nThird line.";
http://php.net/types.string <-- extremely useful reading
this article is a cornerstone of PHP knowledge and it's just impossible to use PHP without it.
unlike most of manual pages which are are just for quick reference, this very page is one which every developer should learn by heart.