I have an issue. I'm trying to write a string with ASCII text like this: '/\'. But whenever I do that the backslash screws up the code by canceling out the quote defining it a string therefore screwing it up. Is there anyway to cancel out the backslash so it doesn't cancel out the quote? Thanks guys!
The \ is special character, that says: 'The next character has special meaning'.
So if you want to dispaly \ you should write... \\ to get one \ in output
It would be very helpful to show what you have tried, but this will produce the exact output you requested (as shown by SO)
echo '\'/\\' . "'\n" ;
'/\'
It should also give you an idea of how backslash escaping works in different types of strings.
A great solution when writing stuff like that is HEREDOC. Inside a heredoc block you don't need to worry about escaping anything, it will just be text.
For example:
echo <<<TEXT
/|\/|\/|\/|\/|\/|\/|\/|\/|\/|\
TEXT;
There is one catch. PHP will break if you don't align the echo at the start of the line, or if the TEXT; is not aligned at the start of the line.
Heredoc can also be assigned to a variable, like so:
$var = <<<SOME_MORE_TEXT
/|\/|\/|\/|\/|\/|\/|\/|\/|\/|\
SOME_MORE_TEXT;
Finally, HEREDOC preserves tabs and spaces. Which also might come in handy when doing ASCII art.
Refer to: http://php.net/manual/en/language.types.string.php for more information.
You only need to escape the final one when using single quotes.
$var = 'backslash\backslash\backslash\\';
// output is:
// backslash\backslash\backslash\
Related
I'm encountering a problem involving escaping character that I think it's not simple at all. If this is done in javascript, nothing to say but the context is using echo command (in PHP) to write javascript code like this:
echo "<script>document.getElementById('spanID').innerHTML=\"$x\"</script>";
$x is a variable in PHP environment, which can contain both single and double quotes. What I do here is:
1. Keep the $x not change, and if $x contains any double quote, the above code won't work, the text echoed may look like:
<script>document.getElementById('spanID').innerHTML="leftside"rightside"</script>;
I supposed $x = leftside"rightside, and you can see it surely won't work.
Escape the double quotes in $x (change all " to "), then the text echoed may look like this:
document.getElementById('spanID').innerHTML="leftside"rightside";
The " won't be converted to " when it is assigned to innerHTML attribute of a Span (for e.g), so instead of my want, the innerHTML of my SPAN should be leftside"rightside, it will be leftside"rightside.
If I change the " to ' in the original echo, like this:
echo "<script>document.getElementById('spanID').innerHTML='$x'</script>";
It is the same because $x here can contain both single and double quotes.
I don't find out any other ways to escape quotes in this case. Could you please help me out?
Thanks!
You need to put between the quotes a string that is a valid string of JavaScript containing valid (and safe) HTML.
Your best option is to not use innerHTML and instead use document.createTextNode which means you only need to slash-escape the content.
Otherwise, you need to HTML escape, then slash escape the content. For correctness, your slash-escaping function should escape at least double-quotes, backslashes, and all JavaScript newlines (U+A, U+D, U+2028, U+2029). I believe PHP's addslashes does not handle U+2028 or U+2029 by default but How to escape string from PHP for javascript? has some alternatives.
To put it all together:
$x_escaped = json_encode($x, JSON_HEX_TAG);
echo "<script>document.getElementById('spanID').appendChild(document.createTextNode($x_escaped))</script>"
should do it. The JSON_HEX_TAG makes sure that $x_escaped will not contain </script> or any other content that prematurely ends your script tag. </script> will instead become \u003c/script\u003e.
I have a php var which, when echoed, writes a JS function into the source of a page. The function loops through a CSV and so it has the following line within it:
$str="var lines = data.split('\n');";
At the present time, when echoed, I get this 'correct' JS written into the source:
var lines = data.split('
');
Instead, I want to echo the literal string \n into the source of the page.
Can anyone point me in the right direction? Thanks.
Escape the slash.
"\\n"
So that it is treated as a slash instead of an escape character.
Try this:
$str="var lines = data.split('\\n');";
you can escape \ like this: \\.
But I would put the whole JS functionality into a .js file, include that from the generated HTML, and call the specific function when needed. And generate a minimalistic js code, like var config = {....} if I have to communicate some page related information.
You almost never need dynamically generated JS code. It's a lot harder to read and you're wasting CPU and network bandwidth...
Either the solutions in the earlier answers, or invert the quotes by using single quotes as the PHP string delimiter:
$str='var lines = data.split("\n");';
Or escape the inner quotes, if you want to keep single quotes for javascript as well when using single quotes as the PHP string delimiter.
$str='var lines = data.split(\'\n\');';
See the docs on quoted strings in PHP as well about how single quoted strings and double quoted strings behave differently.
I want to do output like this:
echo <<<END
$monkey
END;
where the output would be '$monkey' (i.e. all text up to END is treated as normal text, and not parsed)
I want to avoid escaping or modify any of the text up until the END.
is that possible?
e.g. ideally I want to do something like this
echo '
loads of lines here
';
In PHP 5.3, you can use nowdoc:
$var = <<<'END'
$monkey
END;
Otherwise, you'll always to worry about escaping something (all the escape codes and the dollar sign on heredoc, the same plus double quotes on double quote strings and backslashes and single codes in single quoted strings).
Even with heredoc or nowdoc, you would still have a problem if you have a literal END; in the text you want to display. The only foolproof way is to put your literal text in a separate file, read it into a variable (with e.g. file_get_contents), and then echo that variable.
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.
I'm learning PHP and MySQL together from Head First PHP & MySQL and in the book, they often split their long strings (over 80~ characters) and concatenate them, like this:
$variable = "a very long string " .
"that requires a new line " .
"and apparently needs to be concatenated.";
I have no issue with this, but what strikes me odd is that whitespace in other languages usually don't need concatenation.
$variable = "you guys probably already know
that this simply works too.";
I tried this and it worked just fine. Aren't line breaks always interpreted with a space at the end? Even the PHP manual doesn't concatenate in the echo examples if they span over one line.
Should I follow my book's example or what? I can't tell which is more correct or "proper" since both work and the manual even takes a shorter approach. I also would like to know how important is it to keep code under 80 characters in width? I have always been fine with word warp since my monitor is pretty large and I hate my code getting cut short when I have the screen space.
There's 3 basic ways of building multiline strings in PHP.
a. building string via concatenation and embedded newlines:
$str = "this is the first line, with a line break\n";
$str .= "this is the second line, but won't have a break";
$str .= "this would've been the 3rd line, but since there's no line break in the previous line..."`
b. multi-line string assignment, with embedded newlines:
$str = "this is the first line, with a line break\n
this is the second line, because of the line break.
this line will actually is actually part of the second line, because of no newline";
c. HEREDOC syntax:
$str = <<<EOL
this is the first line
this is the second line, note the lack of a newline
this is the third line\n
this is actually the fifth line, because the newline previously isn't necessary.
EOL;
Heredocs are generally preferable for building multi-line strings. You don't have to escape quotes within the text, variables are interpolated within them as if it was a regular double-quoted string, and newlines within the text are honored.
In PHP long strings don't need concatenation but keep in mind that:
$variable = "you guys probably already know
that this simply works too.";
is the equivalent of
$variable = "you guys probably already know\nthat this simply works too.";
The newline is just the same in these 2 examples (if your system uses \n as a newline - Windows uses \r\n).
So to answer your question, no, you don't have to break large strings in many smaller ones. Doing so is just a matter of preference (which I don't really often see).
The 80 char "limit" is throwback to the old days where terminal screens had an 80 char width. If you ever need to edit something in a narrow width terminal, respecting 80 chars can be helpful. However, if longer than 80 char lines wrapping are causing you headaches in your editor, Don't follow that convention.
When you have a multi-line string as in your second example, the string will be exactly as you type it in your editor. If you have a whole bunch of spaces before your retrun char, those will be in your string var. The only exception to this is if your editor is doing line wrapping, then there is not actually a return char in the string, and it won't show up in the variable.
PHP syntax allows literal line feeds in the strings. Your second example equals this:
you guys probably already know[LF][SPACE][SPACE][SPACE][SPACE]that this simply works too.
where [LF] will be \r\n or \n depending on your editor settings. Those redundant spaces may be an issue or not (not everything is HTML), but it's not the same as concatenating.
No.
1) open quotes
2) write as much as you need, adding spaces, tabs, whatever else
3) close quotes.
If you're using the same quotes within, escape them with \
"Jane said \"It's hot today!\"";
or
'Jane said "It\'s hot today!"';