PHP : Using single quotes and double quotes in single string - php

How can i use string like below code.
$str = 'Is yo"ur name O'reil"ly?';
The above code is just an example..I need to use big html template which contains single and double quotes.I tried Addslashes php method but when i use single and double quote string in that function i get syntax error.Please help me.
Note : my realtime usage is json data like below.
$string = "
<html>
...
<b:if cond='data:blog.pageType == "item"'>
..
";
$string = '{"method":"template","params":{"1":"'.$string.'"},"token":"12345"}';

You can use a heredoc for that:
$string = <<<EOM
<html>
...
<b:if cond='data:blog.pageType == "item"'>
..
EOM;
If you wish to prevent variable interpolation as well you can use nowdoc (since 5.3):
$string = <<<'EOM'
<html>
...
<b:if cond='data:blog.pageType == "item"'>
..
EOM;
Both heredoc and nowdoc have specific formatting requirements, so be sure to read the manual properly.

I used heredoc to do the same like
$string = <<< EOF
'Is yo"ur name O'reil"ly?'
EOF;

You can use heredoc like this:
$str = <<< EOF
'Is yo"ur name O'reil"ly?'
EOF;

Related

Escaping $ in HEREDOC string with PHP

I have something like this
$var = <<<HEREDOC
..."request": ${"hello"}...
HEREDOC;
Of course PHP thinks ${"hello"} is a variable and it fails to load.
How to escape the $?
The same way you escape almost anything in a string
$var = <<<HEREDOC
..."request": \${"hello"}...
HEREDOC;
echo $var;
RESULT
..."request": ${"hello"}...
Is that what you want?
$var = <<<HEREDOC
..."request": \${"hello"}...
HEREDOC;

php nested heredoc and escaping variables

I am using heredoc to create a php file which needs to use heredoc in the generated file as the file will create other files.
The <<<EOD bit works fine and I can see all the variables properly escaped.
The problem I'm having is the nested heredoc <<<EOL where \$languageStrings isn't escaped
If I use \$languageStrings and run the generated file ddd.php, the output is this:
<?php
= Array (
'LBL_LOCATION_INFORMATION' => 'Basic Information',
'LBL_CUSTOM_INFORMATION' => 'Custom Information',
'SINGLE_' => ''
);
if i use \\$languageStrings trying to esacpe the backslash i get:
<?php
\ = Array (
'LBL_LOCATION_INFORMATION' => 'Basic Information',
'LBL_CUSTOM_INFORMATION' => 'Custom Information',
'SINGLE_' => ''
);
How can I correct this so i get $languageStrings = Array (? I did think about trying to open the file and insert into a specific line but the file will always be different.
I'm open to suggestions
Here is an example of my heredoc
$text = <<<EOD
This is some text
This is some more text
This is a \$variable //outputs this is a $variable
This is some more text
EOD;
$text .= <<<EOD
\n
\$targetpath = 'modules/' . \$moduleInstance->name;
if (!is_file(\$targetpath)) {
mkdir(\$targetpath);
mkdir(\$targetpath . '/language');
// create the language file
\$languagepath = 'languages/en_us';
\$languageContents = <<<EOL
<?php
\$languageStrings = Array (
'LBL_LOCATION_INFORMATION' => 'Basic Information',
'LBL_CUSTOM_INFORMATION' => 'Custom Information',
'SINGLE_\$moduleInstance->name' => '\$moduleInstance->name'
);
EOL;
file_put_contents(\$languagepath . '/' . \$module->name . '.php', \$languageContents);
}
EOD;
file_put_contents('ddd.php', $text);
I fixed it by creating a variable outside of the heredoc
$strings = '\$languageStrings';
and replacing \$languageStrings with $strings = Array ( in the heredoc string
The output is what I expected
Need a single quotes like Heredoc. This name is Nowdoc.
Nowdocs are to single-quoted strings what heredocs are to double-quoted strings.
$foo = "bar";
echo <<<STR
str $foo
STR;
echo <<<'STR'
str $foo
STR;
OR
echo "str $foo";
echo 'str $foo';
Expected Result:
->str bar
->str $foo
Since PHP 5.3.0, the opening Heredoc identifier may optionally be double quotes
<<<"FOO"
FOO;
same as
<<<FOO
FOO;
I prefer use every time double-quoted heredoc for intelligibility, although it is optional.
Doc says: php.net
Nowdocs are to single-quoted strings what heredocs are to
double-quoted strings. A nowdoc is specified similarly to a heredoc,
but no parsing is done inside a nowdoc. The construct is ideal for
embedding PHP code or other large blocks of text without the need for
escaping. It shares some features in common with the SGML construct, in that it declares a block of text which is not for
parsing.
A nowdoc is identified with the same <<< sequence used for heredocs,
but the identifier which follows is enclosed in single quotes, e.g.
<<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc
identifiers, especially those regarding the appearance of the closing
identifier.

Using multiple quotations in PHP codes

Let's say this is my script down here, as you can see I've used multiple " and '. These quotations conflict in ending the current php variable, so it basically sees this:
$message = "<?php echo '<div class="
As a string, whilst the quotation is only to define the class, not to end the variable. I've tried using ' but then it conflicts with the echo, so I'm kinda stuck at the moment.
<?php
$message = "
<?php
echo '<div class="gebruiker">';
$fh = fopen('_gebruiker.txt','r');
while ($line = fgets($fh)) {
echo($line);
}
fclose($fh);
echo '</div>';
?>
";
**MORE PHP CODE HERE**
?>
How can I use multiple quotations in one PHP script without them having conflicts.
If you use single quotes outside, you need to escape all single quotes inside, but can use double quotes and the dollar char without escaping.
If you use double quotes outside, you need to escape all double quotes and dollar chars inside, but can use single quotes without escaping.
If you use a heredoc string, you need to escape dollar chars but can use both single and double quotes without escaping.
If you use a nowdoc string, you do not need to escape anything unless you have FOO; in the string at the beginning of a new line.
So the solution is to use a nowdoc string:
$message = <<<'EOF'
your stuff with " or ' or $ here!
EOF;
Adding a backslash so PHP can recognize just only double quotes or quotes when escaped.
Example:
echo "<div class=\"gebruiker\">";
I suggest using either Heredoc or Nowdoc
Example
$foo = 'test';
// Heredoc
$here = <<<HERE
I'm here, $foo!
HERE;
// Nowdoc
$now = <<<'NOW'
I'm now, $foo!
NOW;
Heredoc will print the contents of $foo when echoed while Nowdoc will simply echo $foo.
In the references I added below you can do more reading up on this subject.
References:
php.net - strings
stackoverflow - advantages of heredoc vs nowdoc
You can escape the quotes with a slash character like so: \"
This should work, you can't open Php tag without closing before.
<?php
$message = '<div class="gebruiker">';
$fh = fopen('_gebruiker.txt','r');
while ($line = fgets($fh)) {
$message .=$line.'<br/>';
}
fclose($fh);
$message.='</div>';
echo $message;
**MORE PHP CODE HERE**
?>

Does heredoc output variables which contains quotes?

I am using this:
$variable = "Name is \"Bob\"";
$message = <<<EOF
<input type="text" value="$variable">
EOF;
And the result is :
Actually, this is synthetic example and I am working with db. But I tried: this synthetic example works (to simulate problem, actually it shows that what I am doing is not working).
Yes, the quotes will appear in the HTML.
Since the quotes will end the attribute value, you'll make the HTML invalid.
You need to make the variable HTML-safe with htmlspecialchars().
You are generating invalid HTML:
<input type="text" value="Name is "Bob"">
Please use htmlspecialchars() to encode $variable before insertion.
A heredoc is just a convenient shortcut for a multi-line echo. It doesn't care WHAT'S in the string, it'll just be output.
There is NO difference between the following two constructs:
$foo = "A string with an \" embedded quote";
echo <<<EOL
Hello, $foo, how are you
EOL;
echo "Hello, $foo, how are you";
The only real difference is that you don't have escape quotes in the rest of the string:
echo <<<EOL
This is a "quoted phrase" within a sentence
EOL;
echo "This is a \"quoted phrase\" within a sentence";

How can I store PHP code inside a 'heredoc' variable?

I would like to store the following code inside a HEREDOC variable:
<?php
$var = 'test';
echo $var;
?>
like this:
$hered = <<<HERED
<?php
$var = 'test';
echo $var;
?>
HERED;
The problem is that HEREDOC works like double quotes, "" - that means each dollar sign ($) has to be replaced with \$...
Is there a way to use HEREDOC without performing such an operation?
Yes, there is. Check out the nowdoc syntax:
$hello = 'hey';
$echo <<<'EOS'
$hello world!
EOS;
//Output: $hello world
It can be done using \:
echo <<<HEREDOC
<?php
\$var = 'test';
echo \$var;
?>
HEREDOC;
I know there's now doc, but for example my current use case needs heredoc, because some dollars need to be escaped and some not:
$variableNotToEscape = 'this should be output';
echo <<<HEREDOC
$variableNotToEscape
\$variableNotToEscape
HEREDOC;
Which returns
this should be output
$variableNotToEscape

Categories