> Articles > PHP articles > Avoiding prefixing $, \, ", ' symbols with slashes
Avoiding prefixing $, \, ", ' symbols with slashes
In PHP a string literal can be specified in several ways.
- Single quoted:
$str = 'some text, single \'quote, $dollar sign , "double quotes"';
only single quoted have to be prefixed by slashes inside that string.
- Double quoted:
$str = "text, double quote\", \$dollar sign, 'single quotes'";
dollar sign, double quotes and slash should be prefixed by slashes here.
- Heredoc syntax:
$str = <<<EOD some text here "quotes', \$ dollar sign EOD;
only dollar sign has to be prefixed by slash, also \r is not allowed inside.
Starting from PHP 4 we can control the way PHP buffers the output.
We can stop immediate output at any moment, and redirecting all the output to internal
PHP buffer, later we can read from that buffer.
That allows us to specify a string literal not prefixing any symbols
with slashes, but that way we can not use <? and ?> inside the text block.
<? ob_start(); ?>
Anything here, $dollar sign, "any quotes', slashes \ /, ...
<? $str = ob_get_contents(); ob_end_clean(); ?>
This is an example of using PHP buffering to avoid extra slashes, saving text
in the variable
$str.
The only disadvantage is that it's impossible to use PHP tags in a straight way
inside that text block.
There is a workaround for that, replacing
<? and
?>
with
<?='<?';?> and
<?='?>';?>
Copyright © Val Samko, DigiWays. Written by Valentin Samko mailto:val@digiways.com
|