Javascript string literal error - php

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.

Related

escape sequences are not working in php

if im not wrong \n representation means that a newline as <br> .But when i use <br> or another tags they work properly but escape sequences.
example
echo "write somethings<br>";
echo "about coding";
above example works fine but when i try to use escape sequences none of them are not working
echo "write something\n";
echo "about coding";
it's just an example for newline character and the other escaping characters dont work as \n.What is the real logic on this case?
\n and other similar escape sequences are not part of HTML. You should use HTML escape sequences. These can be found here: http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php
So only your <br> tag works but \n is not
No, this is an example of HTML rules.
Putting \n in a PHP string and then outputting it as HTML will put a new line character in the HTML source code. It's just line pressing return when writing raw HTML.
HTML puts no special meaning on the new line character (at least outside of script elements and elements with various non-default values of the CSS white-space property) and treats it like any other white space character.
<br>, on the other hand, is a line break element (but usually an indication that you should be using a block level element around the content instead).
HTML ignores carriage return and linefeed characters, treating them as whitespace. If you want to use display a string formatted with "\n" you can use nl2br to convert it, e.g.
echo nl2br("this is on\ntwo lines");
If you look at this in the browser it wont work : browser knows only HTML for display (<br>) but not escape like \n or \r

How to insert backslashes before all line breaks in a string?

I am building multi-line strings in PHP that need to be used in Javascript functions, so I echo out the strings and they appear where they should, but the problem I'm having is that Javascript multi-line strings must have a backslash \ at the end of each line.
Aside from hard-coding the backslashes in (which I can't do since the strings are used outside of the Javascript functions, too) how can I add a backslash before each line break in the string?
Run the string through the json_encode function to generate a JavaScript string. Don't try to write your own routine to make a string safe for JS.
str_replace("\r\n","\\\r\n",$str)

Saving source code from HTML textarea to file

I am saving C++ code from a textarea of an HTML form using PHP.
The problem is if my code is like below,
printf("%d\n");
printf("%d\n");
the code that is saved to the file is like this:
printf(\"%d\\n\");\nprintf(\"%d\\n\");
I want the original code to be saved in the file. If I use,
$sourceCode = str_replace('\n',"\n", $sourceCode);
$sourceCode = str_replace('\"',"\"", $sourceCode);
the result is like below (saved in the file):
printf("%d\
");printf("%d\
");
It is clear that replacing \n in the source code replaces all the HTML created \n along with the \n that user gave as input (the original text). The only difference is user's input has an additional \ before the \n, that is \\n.
How can I resolve the problem such that only the implicit escape characters will be replaced, but the explicit escape characters, that the user wrote himself, will not be changed?
As mentioned by KenB, we need to see the PHP code that you are using to process the form input.
Processing Form Input
It looks to me like addslashes has been used on the form input.
If you are doing that in your code, don't. This is not the proper way to process form input. Instead, you should use the correct function (such as htmlspecialchars or mysqli_real_escape_string) to escape the input before you use it. Read about addslashes.
If you are using an older version of PHP where magic_quotes_gpc is on by default, then you should fix that. Read about 'Disabling Magic Quotes'.
Stripping Out the Slashes
If you have no control over the code that is adding the slashes, then you can remove them with a simple PHP function called stripslashes.
$sourceCode = stripslashes($sourceCode);
Read about stripslashes.
Understanding Escape Sequences
Your str_replace code shows a lack of understanding about escape sequences and/or a lack of understanding about single vs double quotes.
In the following code, a literal \n is replaced with a line break. With the double quotes, PHP interprets the \n as an escape sequence rather than a literal string.
$sourceCode = str_replace('\n',"\n", $sourceCode);
What you want is to replace a literal \\n with a literal \n. Note that to specify a literal backslash it must be doubled; hence the triple backslash you see below.
$sourceCode = str_replace('\\\n', '\n', $sourceCode);
And although this next line accomplishes what you wanted...
$sourceCode = str_replace('\"',"\"", $sourceCode);
...it could have been written differently. The following code is easier to read, saves you having to escape the literal ", and doesn't require PHP to interpret the string.
$sourceCode = str_replace('\"', '"', $sourceCode);
I've given the above code as examples to explain how PHP interprets escapes sequences, but don't use them. Either avoid adding the slashes in the first place or strip them using the proper function, as explained in the first part of this answer.
Read more about escape sequences and quoting strings.
The Literal \n Between Lines
I'm not sure what you are doing to add the literal \n between the lines. We'd need to see your code. But to remove it after the fact, you could try the following
$sourceCode = str_replace(';\n', ";\n", $sourceCode);
Of course, then you'd likely need to correct other C++ end-of-line sequences. So it is better to not add it in the first place.

Can't see new lines on textarea - what could the problem be?

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.

Error message "Unterminated string literal"

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.

Categories