Have I misunderstood what heredoc should do? - php

I'm very new to PHP so I know I am missing something obvious here -
I thought the heredoc function is supposed to retain formatting, line breaks, etc.
But whenever I test it, while it parses, there is no formatting.
I've tried lots of different scripts including copy-and-pasts from sources such as PHP.net and W3schools - so I know there is nothing wrong with the scripts. Can't google up an answer to this one - probably because it's too obvious?? (BTW, testing with MAMP). Thanks.

HEREDOC is not a function, it is a method for specifying string delimiters that allows you to forgo escaping quotes within the heredoc (I like it because good text editors will syntax highlight their contents based on the heredoc name).
HEREDOCs do preserve all whitespace, newlines, etc. I think you are probably looking at the results in a browser. Browsers generally trim all whitespace, newlines, spaces, and tabs included, down to a single space. Try looking at it on the command line, a text email, or a text file.

It will produce a string identical to the one you set.
However, browsers render multiple whitespace condensed to one space character. This is by design.
To preserve your spaces, you can use the pre element (assuming default browser stylesheet) or white-space: pre CSS property.
<div style="white-space: pre">
<?php echo <<<A
some text
preserved
just
how
you want it.
A; ?>
</div>
jsFiddle.

Because you said "testing with MAMP" I assume, that you use your webbrowser to display the content. Thats a slightly wrong approach, because the webbrowser itself strips down any unnecessary whitespaces. Look at the source of the page you display in your browser and you will see the "real" content.

It does, but only for what it outputs.
If it outputs HTML, then that HTML is going to be interpreted by a browser using the normal rules for handling whitespace.

Related

how to replace '\\\' to '\'?

my code is not working ? and i dont want to use str_replace , for there maybe more slashes than 3 to be replaced. how can i do the job using preg_replace?
my code here like this:
<?php
$str='<li>
<span class=\"highlight\">Color</span>
Can\\\'t find the exact color shown on the model pictures? Just leave a message (eg: color as shown in the first picture...) when you place order.
Please note that colors on your computer monitor may differ slightly from actual product colors depending on your monitor settings.
</li>';
$str=preg_replace("#\\+#","\\",$str);
echo $str;
There is merit in the other answers, but to me it looks like what you're actually trying to accomplish is something very different. In the php code \\\' is not three slashes followed by an apostrophe, it's one escaped slash followed by an escaped apostrophe, and in the rendered output, that's exactly what you see—a slash followed by an apostrophe (with no need to escape them in the rendered html). It's important to realize that the escape character is not actually part of the string; it's merely a way to help you represent a character that normally has very different meaning in within php—in this case, an apostrophe normally terminates a string literal. What looks like 4 characters in php is actually only 2 characters in the string.
If this is the extent of your code, there's no need for string manipulation or regular expressions. What you actually need is just this:
<?php
$str='<li>
<span class="highlight">Color</span>
Can\'t find the exact color shown on the model pictures? Just leave a message (eg: color as shown in the first picture...) when you place order.
Please note that colors on your computer monitor may differ slightly from actual product colors depending on your monitor settings.
</li>';
echo $str;
?>
Only one escape character is needed here for the apostrophe, and in the rendered HTML you will see no slashes at all.
Further Reading:
Escape sequences
The root of this problem is actually in how it was written into your database and likely to be caused by magic_quotes_gpc; this was used in older versions and a really bad idea.
The best fix
This requires a few steps:
Fix the script that puts the HTML inside your database by disabling magic_quotes_gpc.
Write a script that reads all existing database entries, applies stripslashes() and saves the changes.
Fix the presentation part (though, that may need no changes at all.
Alternative patch
Use stripslashes() before you present the HTML.
use this pattern
preg_replace('#\\+#', '\\', $text);
This replaces two or more \ symbols preceding an ' symbol with \'
$theConvertedString = preg_replace("/\\{2,}'/", "\'", $theSourceString);
Ideally, you shouldn't have code causing this issue in the first place so I would have a look at why you have \\' in your code to begin with. If you've manually put it in your variables, take it out. Often, this also happens with multiple calls to addslashes() or mysql_real_escape_string() or a cheap hosting providers' automatic transformation of all POST request variables to escape slashes, combined with your server side PHP code to do the same.

In PHP, how do I express a string literal on multiple lines without the new lines appearing in the rendered text?

Sometimes in PHP when I need to assign a large string literal to a variable, I break the quoted string into multiple lines so it can be read without scrolling 300 characters to the right. My problem is that PHP includes the new-line in the actual string when it is rendered in the application. Is there any way to escape the new line or is there a better way of expressing a string literal on multiple lines? I'm aware that I could use concatenation, but I was hoping for a more elegant solution.
Running on Debian if it matters.
On large string i prefer to use the heredoc style, also you can see a couple alternatives in the PHP Documentation about Strings
The str_replace('\n',"",$string); command replaces the newline. See PHP documentation.

Removing Break Lines

I've asked this question before but I didn't seem to get the right answer. I've got a problem with new lines in text. Javascript and jQuery don't like things like this:
alert('text
text);
When I pull information from a database table that has a break line in it, JS and jQuery can't parse it correctly. I've been told to use n2lbr(), but that doesn't work when someone uses 'shift+enter' or 'enter' when typing text into a message (which is where I get this problem). I still end up with separate lines when using it. It seems to correctly apply the BR tag after the line break, but it still leaves the break there.
Can anyone provide some help here? I get the message data with jQuery and send it off to PHP file to storage, so I'd like to fix the problem there.
This wouldn't be a problem normally, but I want to pull all of a users messages when they first load up their inbox and then display it to them via jQuery when they select a certain message.
You could use a regexp to replace newlines with spaces:
alert('<?php preg_replace("/[\n\r\f]+/m","<br />", $text); ?>');
The m modifier will match across newlines, which in this case I think is important.
edit: sorry, didn't realise you actually wanted <br /> elements, not spaces. updated answer accordingly.
edit2: like #LainIwakura, I made a mistake in my regexp, partly due to the previous edit. my new regexp only replaces CR/NL/LF characters, not any whitespace character (\s). note there are a bunch of unicode linebreak characters that i haven't acknowledged... if you need to deal with these, you might want to read up on the regexp syntax for unicode
Edit: Okay after much tripping over myself I believe you want this:
$str = preg_replace('/\n+/', '<br />', $str);
And with that I'm going to bed...too late to be answering questions.
I usually use json_encode() to format string for use in JavaScript, as it does everything that's necessary for making JS-valid value.

PHP - Comments inside <?php echo <<<EOF

How do I comment out if I use this syntax?:
<?php
echo <<<EOF
Is it //Comment or <!-- Comment --> or something else?
EOF;
?>
I'm a little bit confused.
Thank you
You can't. The point of HEREDOC is that anything inside it will be part of the string. It exists to avoid having PHP meta characters (including comments) treated as such. Anything you put inside it will appear in the string (and thus, in this instance, be echoed to wherever the output is directed).
If the output is HTML, then you could include an HTML comment in it. That will still appear in the output, but anything parsing the HTML will treat it as a comment. Likewise, if the content is JS then you can use a JS comment, and so on.
You can't use a comment inside the heredoc syntax.
http://en.wikipedia.org/wiki/Here_document
It's a way to specify a literal string, literally.
Everything between the heredoc delimiters is interpreted literally, and that's the point of the heredoc syntax. Any HTML comments will be outputted as well, and PHP doesn't care that the browser will omit them.
It depends on the type of output you are echoing to. If you're echoing that data to an HTML page, you can use the <!-- --> syntax and the browser will see that as a comment. If you're outputting to a plaintext file, everything within the heredoc will be output (in truth, everything will be output when writing HTML as well, just the browser will interpret the HTML comment).
When I'm using heredoc syntax and need to comment the information inside, I typically use a (PHP-style) comment before the heredoc and reference any specific lines within by their line number, relative to the heredoc:
/* Write out default INI file.
* L002: Log level. Possible values: debug,info,warning,error.
*/
echo <<<EOF
[global]
logging = error
...
EOF
Hope that helps.
To my knowledge you can't put comments inside the HEREDOC block.
According to PHP documentation at http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc "Heredoc text behaves just like a double-quoted string, without the double quotes.".. and you can't put comments inside a double-quoted string.
Actually, there is a circuitous way of commenting inside an echo.
You can use the following syntax
<?php
'.(/*comment here*/ NULL).'
This line will be read as inner php and can contain comments. NULL has to be included because everything inside the inner php requires a value. NULL is the most convenient choice, since you dont actually want a value, just a comment.
Actually, you cannot use PHP comments in the middle of the string (neither in double quoted nor in single quoted nor heredoc strings). They will be shown literally.
In some rare cases it may be useful to simulate comments and strip them later from the string. For instance it could be useful if you are creating some kind of template engine. But certainly in most cases you should not do this, as it's bad practice.
You can build up your string using "\r\n" (using double quotes for the line breaks) and put the comments on the same line after the string, e.g.
echo "line1\r\nline2"; //this outputs two lines

What is <<<_END?

I'm new to PHP and don't understand what the point of <<<_END is. Could someone please explain when this should be used? I've looked at various examples and they all seem to have HTML embedded within them. But I can use HTML without the <<<_END tags, so why should I use them? I tried searching the manual, but I keep finding the end() method for arrays.
It's the start of a heredoc. you can do:
$data = <<< _END
You can write anything you want in between the start and end
_END;
_END can be just about anything. You could put EOF or STUFF. as long as you use the same thing at the start and the finish.
This signifies the beginning of a heredoc (a multi-line string that allows you to use quotation marks in the middle, unescaped) that ends when you encounter the _END
It can be useful to define HTML in one of these if the goal is to assign it to a variable or pass it to a function rather than printing it to the web server immediately.
That syntax is called heredoc
<<<_END
some text
_END
Basically, it's a way of writing a string without worrying about escaping quotes and so on.
As you've mentioned, it doesn't really provide a lot of benefit over other string formats - although, it does mean you can write a block of HTML without escaping out of PHP with ?>
It also isn't too popular as its use generally goes against the practice of seperating content from logic by embedding the content in the middle of your script.
Does this help? http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc
It allows you to echo out a block of text (just the same as with echo "words";), but without using the beginning/ending quotes, and without having to escape contained double quotes. Read the manual link above for more detail.
It's a heredoc. It's just a way of defining a string.

Categories